# Shafikul Islam — Full Technical Profile, Case Studies & Architecture Corpus > Complete machine-readable corpus for https://shafiktanbir.com (shafiktanbir). Dynamic snapshot updated: 2026-10-26 (42 live technical articles). ## Identity & Contact - **Full Name:** Shafikul Islam (also published as Shafikul Islam Tanbir / shafiktanbir) - **Primary Role:** Backend, Platform & Cloud Infrastructure Engineer (Node.js · TypeScript · Go · PostgreSQL · Kubernetes) - **Experience:** 4+ years of production backend, database performance, and Kubernetes infrastructure engineering (Feb 2022 - Present) - **Location & Overlap:** Dhaka, Bangladesh (UTC+6) — full daily overlap with UK, EU, and APAC teams, plus daily US East overlap through 12:00 PM ET - **Hiring Readiness:** Open to international full-time remote roles via EOR (Deel / Remote.com) or direct B2B invoicing, plus fixed-scope backend/database/Kubernetes consulting sprints - **Email:** shafiktanbir@gmail.com - **Phone / WhatsApp:** +8801630083582 - **Website:** https://shafiktanbir.com - **Sitemap:** https://shafiktanbir.com/sitemap.xml - **Resume (PDF):** https://shafiktanbir.com/resume.pdf - **GitHub:** https://github.com/shafiktanbir - **LinkedIn:** https://www.linkedin.com/in/shafiktanbir/ - **X (Twitter):** https://x.com/shafiktanbir - **LinkedIn Newsletter:** https://www.linkedin.com/newsletters/production-systems-dispatch-7521154793416040448/ - **Engineering Foundation & Origin:** Started self-taught on a second-hand desktop with 2GB of RAM, debugging tight Linux memory limits before moving into 4+ years of CS-equivalent production systems engineering, backed by Canonical Ubuntu Linux, Docker Foundations & PagerDuty DevOps certifications (2026), 13 merged upstream open-source PRs, and 67 active open Cloud & Backend PRs. --- ## Verified 2026 Certifications 1. **Ubuntu Linux Professional Certificate by Canonical** — Canonical & LinkedIn (2026) - Credential ID: `396b528d08a6e7b72ef08d8e2cced2bd3682864ace0e4644ef8056020d6a5276` - Verification URL: https://www.linkedin.com/learning/certificates/396b528d08a6e7b72ef08d8e2cced2bd3682864ace0e4644ef8056020d6a5276 - Self-Hosted PDF Backup: https://shafiktanbir.com/certificates/canonical-ubuntu-linux-2026.pdf - Focus: Ubuntu Server administration, systemd service tuning, storage/LVM management, netplan/UFW networking, and SSH/AppArmor security hardening. 2. **Docker Foundations Professional Certificate** — Docker & LinkedIn (2026) - Credential ID: `0349d88e7423342902fb5cb3d2d48910f68fb6d47bcad312041826489311d89a` - Verification URL: https://www.linkedin.com/learning/certificates/0349d88e7423342902fb5cb3d2d48910f68fb6d47bcad312041826489311d89a - Self-Hosted PDF Backup: https://shafiktanbir.com/certificates/docker-foundations-2026.pdf - Focus: OCI container architecture, deterministic multi-stage builds, Docker Compose service orchestration, volume persistence, and bridge networking. 3. **DevOps Professional Certificate by PagerDuty and LinkedIn** — PagerDuty & LinkedIn (2026) - Credential ID: `327693d67b36cb6b45377492b0a8b1adb1ad6513015cf261c0c26e1a261993f2` - Verification URL: https://www.linkedin.com/learning/certificates/327693d67b36cb6b45377492b0a8b1adb1ad6513015cf261c0c26e1a261993f2 - Self-Hosted PDF Backup: https://shafiktanbir.com/certificates/pagerduty-devops-2026.pdf - Focus: CI/CD delivery pipelines, Infrastructure as Code (IaC), production incident management, on-call response, and SRE operational reliability. --- ## Security, Privacy & Regulated SaaS Compliance - **HIPAA & PIPEDA Healthcare Controls (`emmai.ca`):** Built live PHI workflows including TELUS Health HL7 v3 eClaims adjudication, cryptographic SHA-256 clinical SOAP note sealing (HTTP 403 post-sign immutability), and 72-hour rollback-safe medical chart migrations. - **Multi-Tenant Isolation (SOC 2 / GDPR-Ready):** Enforced PostgreSQL Row-Level Security (RLS) scoped per clinic (`set_clinic_context`), FusionAuth SSO, HttpOnly refresh-token rotation, and dynamic per-tenant RBAC overrides (`user_permission_overrides`). - **Zero-Trust Cloud & CI/CD Hardening:** Shipped Kyverno non-root admission policies, Kubernetes NetworkPolicies, WireGuard encrypted node mesh, Trivy CVE gates, and 4-quadrant DEV/PROD secret isolation. --- ## Verified Employment Chronology (4+ Years) 1. **Infrastructure & Cloud Team Lead — Cansoft Technologies (Oct 2025 - Present)** - Led backend architecture, dynamic multi-tenant subdomain isolation (*.emmai.ca), and K3s cloud deployment for emmai.ca, a HIPAA/PIPEDA healthcare clinic operating system. - Engineered streaming zero-downtime Jane App medical data migrations handling PostgreSQL TOAST JSONB payloads, 3-tier WAN deduplication, and automated 72-hour rollback checkpoints. - Implemented HIPAA/PIPEDA privacy controls: PostgreSQL Row-Level Security (RLS), FusionAuth SSO, HttpOnly token rotation, dynamic RBAC, SHA-256 immutable SOAP note sealing (HTTP 403 post-sign), multi-payer split billing, and TELUS Health HL7 v3 eClaims. - Automated multi-node K3s Kubernetes clusters with Ansible, ArgoCD GitOps, modular Helm charts, Traefik ingress, Kubernetes NetworkPolicies, Kyverno admission policies, Trivy CVE gates, WireGuard node mesh, and Prometheus/Grafana/Alertmanager observability. 2. **Backend Developer — Digital Gregg (Jan 2025 - Sep 2025)** - Engineered REST APIs and GTFS-Realtime / WebSocket vehicle telemetry endpoints for Colorado's statewide intercity bus network (ridebustang.com). - Reduced P95 API response latency by 45% via PostgreSQL composite index optimization, N+1 query elimination, and Redis caching. - Built automated GitHub Actions Docker container pipelines and OAuth2/JWT RBAC hardening. 3. **Full-Stack Developer — Tunnel (Jul 2024 - Dec 2024)** - Developed Node.js/Express backend services and inter-service REST contracts supporting React client applications. - Optimized SQL and MongoDB queries while standardizing local development environments with Docker Compose. - Investigated production defects from structured logs and shipped API validation fixes. 4. **Independent Backend Developer — Remote Contract & Self-Built Ventures (Jan 2023 - Jul 2024)** - Bootstrapped, shipped, and transferred an autonomous micro-SaaS platform; implemented Go + Redis Lua atomic reservation flows eliminating oversell race conditions. - Delivered client backend APIs, JWT/RBAC auth, Redis caching, and containerized deployments on AWS and DigitalOcean VPS instances. 5. **Assistant Technical Trainer — Pc Plus Computer Center (Feb 2022 - Jul 2023)** - Designed and taught backend curricula covering Python, Django, REST APIs, relational SQL schema modeling, and Docker Linux VPS deployments; mentored junior developers. --- ## Merged Upstream Open-Source Pull Requests (13 Upstream PRs · External Peer Review) 1. **upstash/qstash-js#296** (https://github.com/upstash/qstash-js/pull/296) — Rejected empty request URLs and missing body claims in JWT webhook signature verification; merged by @CahidArda. 2. **upstash/qstash-py#61** (https://github.com/upstash/qstash-py/pull/61) — Rejected empty URLs and non-string body claims in Python receiver signature verification; merged by @CahidArda. 3. **resend/resend-rust#148** (https://github.com/resend/resend-rust/pull/148) — Percent-encoded event identifiers safely in Rust SDK request paths; merged by @AntoniosBarotsis. 4. **restatedev/sdk-typescript#814** (https://github.com/restatedev/sdk-typescript/pull/814) — Forwarded per-call headers in doWorkflowHandleCall across durable ingress client calls; merged by @slinkydeveloper. 5. **upstash/vector-js#76** (https://github.com/upstash/vector-js/pull/76) — Prevented mutating caller fetch options when reading vector namespace headers; merged by @CahidArda. 6. **upstash/vector-py#53** (https://github.com/upstash/vector-py/pull/53) — Rejected mixed vector and data queries regardless of batch order; merged by @CahidArda. 7. **checkly/checkly-cli#1574** (https://github.com/checkly/checkly-cli/pull/1574) — Fixed CLI argument parsing edge case where an empty --config= / -c= flag consumed the next positional argument; merged by Checkly Staff Engineer (@sorccu). 8. **checkly/checkly-cli#1566** (https://github.com/checkly/checkly-cli/pull/1566) — Fixed reporter accuracy to include retry counts for unfinished checks on --max-failures; merged upstream by @sorccu. 9. **restatedev/sdk-typescript#810** (https://github.com/restatedev/sdk-typescript/pull/810) — Preserved RestateError.code in RetryableError.from() and PauseError.from(); approved and merged by @slinkydeveloper. 10. **openstatusHQ/openstatus#3003** (https://github.com/openstatusHQ/openstatus/pull/3003) — Ordered status page reports by latest update in getLight with Vitest tests; merged upstream by @mxkaske. 11. **openstatusHQ/openstatus#2988** (https://github.com/openstatusHQ/openstatus/pull/2988) — Sorted monitoring timing phases chronologically in mapTimingPhases with Vitest coverage; merged upstream. 12. **jitsucom/jitsu#1592** (https://github.com/jitsucom/jitsu/pull/1592) — Enabled prepareSource mirror preflight in retl-runner to accept objectMappings; approved and merged by @absorbb. 13. **kubernetes/website#56635** (https://github.com/kubernetes/website/pull/56635) — Official CNCF Kubernetes upstream PR publishing the KYAML announcement post; approved via kubernetes-prow (@lmktfy). ## Selected Active Upstream Pull Requests (67 Open External PRs — Cloud & Go Highlights) 1. **grafana/dskit#1181** (https://github.com/grafana/dskit/pull/1181) — Eliminated deadlock and race when closing FailureWatcher (Go); open, CLA signed, 4/4 CI green. 2. **ClickHouse/ch-go#1245** (https://github.com/ClickHouse/ch-go/pull/1245) — Floored negative Unix timestamp remainders in ToDate32 (Go); open, 27/27 CI green (16x E2E & lint). 3. **temporalio/sdk-go#2923** (https://github.com/temporalio/sdk-go/pull/2923) — Synchronous child workflow initialization & mutex-backed callback queue in WorkflowTestSuite; open, CLA signed, -race & build check green. 4. **livekit/sip#1004** (https://github.com/livekit/sip/pull/1004) — Populated SIPUri.User for inbound tel URIs in ToSIPUri (Go); open, CLA signed, 6/6 CI green. 5. **netbirdio/kubernetes-operator#540** (https://github.com/netbirdio/kubernetes-operator/pull/540) — Persisted setup-key Secrets with owner references before status updates; open, CodeRabbit & 127 tests green. 6. **tailscale/tailscale#22593** (https://github.com/tailscale/tailscale/pull/22593) — Deduplicated captive portal detection health triggers across connectivityImpacted edges; open, DCO signed, -race green. 7. **aquasecurity/trivy#11719** (https://github.com/aquasecurity/trivy/pull/11719) — Parsed explicit falsy tokens in Azure ARM Value.AsBoolValue; open, CLA signed, 78 subtests green. 8. **SigNoz/signoz#13255** (https://github.com/SigNoz/signoz/pull/13255) — Parsing aggregation references in ExtractReferencedQueryNames (Go/ClickHouse); open, CLA signed, reviewed. --- ## Public Benchmark & Architecture Repositories (5 Repositories) 1. **Sneaker-Drop-System** (https://github.com/shafiktanbir/Sneaker-Drop-System) — Go, Redis Lua (EVALSHA 60s TTL), WebSockets, k6. Verified: 0.00% oversell under concurrent go test -race and 2,000-VU k6 stress testing. 2. **K8s-Infra-Hardening** (https://github.com/shafiktanbir/K8s-Infra-Hardening) — Kubernetes, Helm, Argo Rollouts canary progressive delivery, Kyverno zero-trust policies, custom Go Pod Hygiene CLI (Go tests passing, helm lint & CI green). 3. **rust-ecommerce-backend** (https://github.com/shafiktanbir/rust-ecommerce-backend) — Rust, Axum 0.7, Tokio, SQLx pessimistic FOR UPDATE locking, multi-stage cargo-chef non-root Docker build (4,665 RPS across 307k 4-node Hetzner requests, 28.4ms P95, cargo test passing). 4. **rabbitmq-event-driven-architecture** (https://github.com/shafiktanbir/rabbitmq-event-driven-architecture) — Node.js, RabbitMQ progressive Dead-Letter Exchange backoff (10s -> 60s -> poison DLQ), publisher confirms, LRU deduplication (26/26 tests passing). 5. **node-microservices-blueprint** (https://github.com/shafiktanbir/node-microservices-blueprint) — TypeScript, Node.js, RabbitMQ Event-Carried State Transfer, Zod boundary validation, isolated per-service MongoDB databases (48/48 Jest tests passing). --- ## Focused Consulting Offers & Engagement Process 1. **PostgreSQL & API Latency Diagnostic Audit (3-Day Fixed-Scope Diagnostic):** Deep inspection of pg_stat_statements, EXPLAIN ANALYZE plans, N+1 ORM loops, and connection pooling. Delivers prioritized remediation blueprint and exact CREATE INDEX CONCURRENTLY DDL. 2. **Concurrency, Database & K8s Hardening Sprint (1-2 Week Implementation Sprint):** Hands-on composite B-Tree indexing, PgBouncer transaction pooling, Redis caching or Lua atomic locks, multi-stage Docker hardening, and K3s/ArgoCD deployment automation delivered via reviewed GitHub PRs. 3. **Multi-Tenant Backend & Migration Delivery (Embedded Contract Engineering):** Production backend engineering in Node.js, TypeScript, Go, or Python covering tenant isolation, RBAC/JWT security, billing/webhook state machines, and rollback-safe data migrations. ### 3-Step Engagement Workflow 1. 20-minute scoping call (https://shafiktanbir.com/book) covering bottlenecks and target SLAs. 2. Low-risk 3-day diagnostic audit or fixed-scope 1-2 week implementation sprint. 3. Asynchronous GitHub PR delivery with reproducible k6/EXPLAIN ANALYZE benchmarks and operational runbooks. --- ## Hiring & Buyer FAQ - **Who is Shafikul Islam?** A self-taught Backend, Platform, and Cloud Infrastructure Engineer in Bangladesh (UTC+6) who started on a second-hand 2GB RAM desktop and now brings 4+ years of production experience across Node.js, TypeScript, Go, Python, PostgreSQL, Redis, Docker, and Kubernetes (K3s/ArgoCD). - **What differentiates his background?** Verifiable production delivery on emmai.ca (HIPAA/PIPEDA healthcare suite) and ridebustang.com (Colorado transit telemetry), 13 merged upstream PRs across Go/CNCF, TypeScript, Python, and Rust (Upstash 4x, Restate 2x, Checkly CLI 2x, OpenStatus 2x, Resend Rust, Jitsu, Kubernetes) plus 67 open Cloud & Backend PRs, and 2026 certifications from Canonical (Ubuntu Linux), Docker, and PagerDuty (DevOps). - **How can international companies hire or contract him?** Full-time remote via EOR (Deel / Remote.com) or direct B2B contractor invoicing, with 4-6h daily overlap for EU/UK/APAC and US morning sync windows. - **Where can recruiters download his resume or schedule a call?** Resume PDF: https://shafiktanbir.com/resume.pdf | Booking calendar: https://shafiktanbir.com/book --- ## Full Technical Case Studies & Articles (42 Published Articles) ### 1. Automated k6 Load Testing in CI/CD: Catching P95 Latency and Lock Regressions Before Production - **Canonical URL:** https://shafiktanbir.com/blog/automated-k6-load-testing-cicd-catching-p95-latency-regressions - **Category:** SRE & Performance Testing | **Published:** 2026-11-23 | **Read Time:** 2 min read - **Summary:** Why unit tests pass on O(N^2) queries and lock regressions, and how we gate releases with automated k6 threshold assertions against ephemeral staging containers. ## Why Functional Tests Never Catch Concurrency or Cardinality Bugs A SQL query missing a composite index executes in **0.4 milliseconds** when your unit test database contains 10 fixture rows. The exact same query takes **3.2 seconds** when table cardinality reaches 10 million rows or when 200 concurrent virtual users contend for the same row lock. To catch tail-latency regressions before code reaches production, we treat **k6 performance thresholds as binary pass/fail CI gates**. --- ## 1. Declarative SLO Thresholds in k6 Every critical API route has a reproducible **k6** scenario that ramps up concurrent virtual users (**ramping-arrival-rate**) and asserts strict **p(95)** and **p(99)** latency bounds: ```javascript import http from "k6/http"; import { check } from "k6"; export const options = { scenarios: { flash_burst: { executor: "ramping-arrival-rate", startRate: 100, timeUnit: "1s", preAllocatedVUs: 200, maxVUs: 1000, stages: [ { target: 1500, duration: "30s" }, { target: 1500, duration: "60s" }, { target: 0, duration: "15s" }, ], }, }, thresholds: { http_req_failed: ["rate==0.00"], http_req_duration: ["p(95)<25", "p(99)<60"], }, }; export default function () { const res = http.post( `${__ENV.BASE_URL}/api/v1/reservations`, JSON.stringify({ sku_id: "sku_hot_01", qty: 1 }), { headers: { "Content-Type": "application/json" } } ); check(res, { "status is 200 or 409 sold out": (r) => r.status === 200 || r.status === 409, }); } ``` If a PR introduces an unindexed join or widens a database transaction lock that pushes **p(95)** above **25ms**, **k6** exits with code **99** and blocks the release automatically. --- ### 2. Securing B2B SaaS Multi-Tenant Authentication: Short-Lived JWTs, Refresh Token Rotation, and Reuse Detection - **Canonical URL:** https://shafiktanbir.com/blog/securing-b2b-saas-multi-tenant-auth-jwt-refresh-token-rotation - **Category:** Cloud Security & Auth | **Published:** 2026-11-22 | **Read Time:** 2 min read - **Summary:** Why long-lived JWTs cannot be revoked during a credential breach, and how we implemented sub-10-minute access tokens with family-tracked refresh token rotation. ## The Revocation Paradox of Stateless JWTs Stateless JSON Web Tokens (JWTs) are popular because API gateways can verify signatures locally without querying a database on every request. However, if you set a JWT's expiration (**exp**) to 7 or 30 days, **you cannot revoke an individual compromised session** when an employee leaves a client company or a laptop is stolen. --- ## 1. Hybrid Architecture: 10-Minute Access JWTs + Rotating Refresh Token Families We combine the speed of stateless verification with instant revocation control: - **Access Token (10-minute TTL):** Verified in-memory at the API gateway using asymmetric **Ed25519 / RS256** public keys, carrying **sub**, **tenant_id**, and **role_version**. - **Refresh Token (14-day TTL in **HttpOnly; Secure; SameSite=Strict** cookie):** Stored as a **SHA-256 hash** in PostgreSQL inside a **token_family_id** lineage. --- ## 2. Automatic Replay Theft Detection Every time a client calls **POST /auth/refresh**, the server marks the used refresh token as **ROTATED** and issues a brand-new refresh token in the same **token_family_id**. If an attacker steals an older refresh token and attempts to use it after the legitimate user has already rotated it (or vice versa), the server sees a request for an already-**ROTATED** token: ```sql -- If a previously rotated token is presented again, compromise is detected: -- Immediately revoke the entire token_family_id! UPDATE auth_refresh_tokens SET revoked_at = NOW(), revoke_reason = 'REPLAY_DETECTED' WHERE token_family_id = $1 AND revoked_at IS NULL; ``` Both the attacker and the legitimate device are forced to re-authenticate immediately, containing token theft automatically within seconds. --- ### 3. High-Throughput Bulk Ingestion in PostgreSQL: Why Binary COPY Beats Multi-Row INSERT by 14x - **Canonical URL:** https://shafiktanbir.com/blog/high-throughput-bulk-ingestion-postgresql-binary-copy-pgx - **Category:** Database & Performance | **Published:** 2026-11-21 | **Read Time:** 2 min read - **Summary:** Benchmarking single-row INSERT, batched multi-row INSERT, UNNEST arrays, and PostgreSQL binary COPY protocol in Go (pgx.CopyFrom) for ingesting 100,000 rows per second. ## The 65,535 Parameter Limit and Parser Overhead of Multi-Row INSERTs When engineers optimize slow loop inserts in PostgreSQL, they typically switch to multi-row **INSERT INTO table VALUES ($1, $2), ($3, $4)...** batches. While better than row-by-row round-trips, multi-row **INSERT** hits two walls: 1. **PostgreSQL Wire Protocol Limit:** The extended query protocol uses a 16-bit integer for parameter count, crashing with **extended protocol limited to 65535 parameters** if a 10-column table batch exceeds 6,553 rows. 2. **SQL Parser and Planner Overhead:** PostgreSQL still parses, rewrites, and plans a massive SQL syntax tree for every batch. --- ## 1. Streaming Binary Rows Directly with pgx.CopyFrom in Go PostgreSQL's **COPY FROM STDIN (FORMAT BINARY)** bypasses the SQL parser and planner completely, streaming binary tuples directly into heap pages: ```go func BulkIngestTelemetry(ctx context.Context, tx pgx.Tx, rows []TelemetryEvent) (int64, error) { _, err := tx.Exec(ctx, ` CREATE TEMP TABLE staging_telemetry ( tenant_id UUID, device_id VARCHAR(64), metric_val DOUBLE PRECISION, recorded_at TIMESTAMPTZ ) ON COMMIT DROP; `) if err != nil { return 0, err } _, err = tx.CopyFrom( ctx, pgx.Identifier{"staging_telemetry"}, []string{"tenant_id", "device_id", "metric_val", "recorded_at"}, pgx.CopyFromSlice(len(rows), func(i int) ([]any, error) { r := rows[i] return []any{r.TenantID, r.DeviceID, r.MetricVal, r.RecordedAt}, nil }), ) if err != nil { return 0, err } tag, err := tx.Exec(ctx, ` INSERT INTO telemetry_events (tenant_id, device_id, metric_val, recorded_at) SELECT tenant_id, device_id, metric_val, recorded_at FROM staging_telemetry ON CONFLICT (tenant_id, device_id, recorded_at) DO NOTHING; `) return tag.RowsAffected(), err } ``` By streaming into a transaction-scoped **TEMP TABLE ... ON COMMIT DROP** via **CopyFrom** and merging with a single set-based **INSERT ... SELECT ON CONFLICT**, we achieved **104,000+ rows/sec** with full conflict deduplication. --- ### 4. Eliminating Redis Hot-Key Bottlenecks and Cache Stampedes with Probabilistic Early Expiration - **Canonical URL:** https://shafiktanbir.com/blog/eliminating-redis-hot-key-bottlenecks-probabilistic-early-expiration - **Category:** Distributed Systems & Caching | **Published:** 2026-11-20 | **Read Time:** 2 min read - **Summary:** Why a single viral tenant or product key can saturate a single Redis shard CPU core, and how we combined XFetch probabilistic recomputation with bounded local L1 caches. ## The Two Failure Modes of High-Traffic Redis Keys Caching solves database load until traffic concentrates heavily on a small set of keys (such as a featured flash-sale catalog or a large enterprise tenant's configuration): 1. **Cache Stampede (Thundering Herd):** At the exact millisecond a hot key's TTL hits **0**, hundreds of concurrent worker goroutines get **redis.Nil** simultaneously and fire expensive SQL queries at PostgreSQL. 2. **Single-Shard Hot-Key Saturation:** Because Redis hashes each key to a single hash slot (**CRC16(key) mod 16384**), 80,000 reads/sec on one key all hit a single Redis node, maxing out its single event-loop core while other cluster shards sit idle. --- ## 1. Probabilistic Early Expiration (XFetch) Instead of waiting for the hard Redis TTL to reach zero, we store the **logical recomputation delta (**deltaMs**)** and **soft expiry timestamp** inside the cached struct. As the key approaches expiration, a single background request probabilistically refreshes the value *before* the hard TTL expires: ```go func ShouldRecomputeEarly(nowMs, softExpiryMs, deltaMs int64, beta float64) bool { if nowMs >= softExpiryMs { return true } randomFactor := rand.Float64() if randomFactor <= 0 { randomFactor = 1e-9 } earlyWindow := float64(deltaMs) * beta * (-math.Log(randomFactor)) return float64(nowMs)+earlyWindow >= float64(softExpiryMs) } ``` --- ## 2. Two-Tier L1 (In-Process Memory) + L2 (Redis) Caching To protect the Redis network hop on ultra-hot read keys, each API pod keeps a tiny **64 MB in-process L1 cache** with a **2-second TTL** and Redis Pub/Sub invalidation. Hot configuration reads resolve in **80 nanoseconds** from local RAM, reducing Redis network commands by **78%**. --- ### 5. Graceful Shutdown in Go and Kubernetes: Draining Active HTTP and Worker Goroutines With Zero 502s - **Canonical URL:** https://shafiktanbir.com/blog/graceful-shutdown-go-kubernetes-zero-502-bad-gateway-deploys - **Category:** Go & Kubernetes | **Published:** 2026-11-19 | **Read Time:** 2 min read - **Summary:** Why Kubernetes rolling updates still return brief 502 Bad Gateway errors, and how to synchronize SIGTERM handling, preStop sleep hooks, and http.Server.Shutdown in Go. ## Why SIGTERM Races Against Kubernetes Endpoint Removal When Kubernetes terminates a pod during a rolling update, two events happen **in parallel**, not in sequence: 1. The kubelet sends **SIGTERM** to your container process. 2. The Kubernetes API server removes the pod's IP from the **EndpointSlice** and notifies the Ingress controller (NGINX, Traefik, or AWS ALB). Propagating that **EndpointSlice** update across every node's iptables/IPVS rules and ingress worker takes **1 to 3 seconds**. If your Go server immediately closes its TCP listener upon receiving **SIGTERM**, any request routed to that pod during those 2 seconds fails with **HTTP 502 Bad Gateway**. --- ## 1. The Kubernetes preStop Hook Synchronization Window Adding a **preStop** lifecycle hook gives the Ingress controller time to stop sending new traffic *before* **SIGTERM** ever reaches the Go binary: ```yaml spec: terminationGracePeriodSeconds: 35 containers: - name: api lifecycle: preStop: exec: command: ["/bin/sh", "-c", "sleep 5"] ``` --- ## 2. Coordinated HTTP and Background Worker Drain in Go Once **SIGTERM** arrives, we drain active HTTP requests first, and only close the RabbitMQ consumer and PostgreSQL connection pool after all in-flight handlers finish: ```go ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() <-ctx.Done() log.Println("SIGTERM received: draining in-flight HTTP requests...") shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() if err := httpServer.Shutdown(shutdownCtx); err != nil { log.Printf("HTTP shutdown error: %v", err) } workerGroup.StopAndWait() dbPool.Close() ``` --- ### 6. Zero-Downtime PostgreSQL Schema Migrations: Expanding Columns and Adding Constraints Without Table Locks - **Canonical URL:** https://shafiktanbir.com/blog/zero-downtime-postgresql-schema-migrations-lock-timeout-not-valid - **Category:** Database Engineering | **Published:** 2026-11-18 | **Read Time:** 2 min read - **Summary:** Why innocent-looking ALTER TABLE statements take an ACCESS EXCLUSIVE lock that freezes production traffic, and the exact expand-and-contract SQL patterns we enforce in CI. ## How a 50-Millisecond DDL Statement Freezes an Entire Database In PostgreSQL, most **ALTER TABLE** operations require an **ACCESS EXCLUSIVE** lock, which conflicts with every other lock mode (including plain **SELECT** queries). Even if the **ALTER TABLE** itself only takes 20 milliseconds, if a 10-second reporting query is currently reading that table, the **ALTER TABLE** waits in the lock queue. While it waits, **every new SELECT, INSERT, and UPDATE on that table is blocked behind the waiting ALTER TABLE**, causing a complete production outage in seconds. --- ## 1. Rule 1: Never Run DDL Without a Strict lock_timeout Every migration script in our pipeline begins with an explicit **lock_timeout** so that if a lock cannot be acquired within 2 seconds, the migration aborts cleanly and retries instead of blocking live customer traffic: ```sql SET lock_timeout = '2000ms'; SET statement_timeout = '60000ms'; ``` --- ## 2. Rule 2: Two-Step Foreign Keys and Check Constraints (**NOT VALID**) Adding a normal **FOREIGN KEY** or **CHECK** constraint scans the entire table while holding an **ACCESS EXCLUSIVE** / **SHARE ROW EXCLUSIVE** lock. Instead, split the migration into two non-blocking steps: ```sql -- Step 1: Metadata-only constraint enforcement for new writes (instant, <5ms) ALTER TABLE orders ADD CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID; -- Step 2: Validate existing historical rows using SHARE UPDATE EXCLUSIVE -- (Does NOT block live SELECT, INSERT, UPDATE, or DELETE queries!) ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer; ``` --- ## 3. Rule 3: Adding NOT NULL Safely in PostgreSQL 12+ Instead of running a blocking full-table scan with **ALTER TABLE ... SET NOT NULL** on a 100-million-row table, add a **CHECK (col IS NOT NULL) NOT VALID** constraint first, run **VALIDATE CONSTRAINT**, and then execute **ALTER TABLE ... SET NOT NULL** - PostgreSQL recognizes the validated check constraint and completes the **SET NOT NULL** instantaneously without re-scanning the table. --- ### 7. Fixing Slow Vector Similarity Search: HNSW Index Tuning (m, ef_construction) in pgvector and Qdrant - **Canonical URL:** https://shafiktanbir.com/blog/fixing-slow-vector-search-hnsw-index-tuning-pgvector-qdrant - **Category:** AI Infrastructure | **Published:** 2026-11-17 | **Read Time:** 2 min read - **Summary:** How we tuned HNSW graph parameters, scalar quantization, and filtered index scans to keep 1536-dimensional embedding retrieval under 12ms P95 at 5 million vectors. ## Why Vector Search Slows Down Past One Million Embeddings A single 1536-dimensional **float32** embedding consumes **6 KB** of raw storage (**1536 * 4 bytes**). At 5 million document chunks, the raw vectors alone require **30 GB**, plus another 15 to 20 GB for the **Hierarchical Navigable Small World (HNSW)** graph links. Once the HNSW graph no longer fits in RAM, every similarity query triggers random SSD page reads, pushing retrieval latency from **8ms to over 900ms**. --- ## 1. Cutting Memory by 50% with halfvec (FP16) Quantization In **pgvector 0.7+** and Qdrant, storing embeddings as 16-bit floats (**halfvec**) instead of 32-bit floats cuts index memory consumption in half while retaining **99.4% recall@10**: ```sql ALTER TABLE knowledge_chunks ALTER COLUMN embedding TYPE halfvec(1536); CREATE INDEX CONCURRENTLY idx_knowledge_chunks_hnsw ON knowledge_chunks USING hnsw (embedding halfvec_cosine_ops) WITH (m = 16, ef_construction = 128); ``` --- ## 2. Balancing Recall vs. Latency at Query Time (**hnsw.ef_search**) - **m = 16, ef_construction = 128:** Builds a high-quality navigable graph during index creation. - **SET LOCAL hnsw.ef_search = 64:** Controls the dynamic candidate list size during **SELECT**. Lowering **ef_search** from 200 to 64 on real-time chat endpoints cut P95 vector query latency from **38ms to 11.4ms** with less than 0.6% difference in top-5 chunk ranking. - **Iterative Scan for Strict Tenant Filters (**hnsw.iterative_scan = relaxed_order**):** Prevents the common "post-filter starvation" bug where filtering by **WHERE tenant_id = $1** on a small tenant returns fewer than **LIMIT k** results from the HNSW graph. --- ### 8. Designing Idempotent Payment and Billing APIs: Preventing Double Charges Under Network Retries - **Canonical URL:** https://shafiktanbir.com/blog/designing-idempotent-payment-billing-apis-preventing-double-charges - **Category:** Backend Architecture | **Published:** 2026-11-16 | **Read Time:** 2 min read - **Summary:** How mobile clients and payment gateways safely retry timed-out POST requests without charging customers twice using atomic PostgreSQL idempotency state machines. ## Why Mobile Retries and Webhook Re-Deliveries Cause Double Charges In distributed systems, **there is no such thing as exactly-once network delivery**. When a client sends **POST /api/v1/payments** and the TCP connection drops *after* your server charged the credit card but *before* the client received the **200 OK** response, the client will retry. To guarantee **exactly-once business execution** over an **at-least-once network**, every state-mutating endpoint must require an **Idempotency-Key** header. --- ## 1. The Idempotency Key State Machine in PostgreSQL Simply checking **SELECT * FROM idempotency_keys WHERE key = $1** before running the payment is broken - two concurrent retries arriving 2 milliseconds apart will both see no record and both charge the card. Instead, we atomically claim the key first using **INSERT ... ON CONFLICT DO NOTHING**: ```sql CREATE TABLE idempotency_records ( idempotency_key VARCHAR(128) NOT NULL, tenant_id UUID NOT NULL, request_hash CHAR(64) NOT NULL, status VARCHAR(24) NOT NULL, -- 'IN_PROGRESS', 'COMPLETED' response_code INT, response_body JSONB, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (tenant_id, idempotency_key) ); ``` --- ## 2. Handling Concurrent In-Flight Retries and Parameter Mismatches When a request arrives with **Idempotency-Key: ord_99281**: 1. **First Arrival:** **INSERT** succeeds with **status = 'IN_PROGRESS'**. The handler executes the payment, updates the row to **status = 'COMPLETED'** with the serialized **response_body**, and returns **201 Created**. 2. **Duplicate Arrival While Still In-Flight (**status = 'IN_PROGRESS'**):** Returns **HTTP 409 Conflict** (**Retry-After: 2**) so the client waits for the original request to finish rather than opening a second charge. 3. **Duplicate Arrival After Completion (**status = 'COMPLETED'**):** Verifies that **request_hash** matches the original request body (returning **422 Unprocessable Entity** if the client reused the same key for a different amount), and immediately replays the stored **response_body** without touching the payment gateway. --- ### 9. Linux Kernel and Sysctl Tuning for 50,000 Concurrent WebSocket and API Connections on Bare-Metal Nodes - **Canonical URL:** https://shafiktanbir.com/blog/linux-kernel-sysctl-tuning-50k-concurrent-websocket-api-connections - **Category:** Cloud Networking & SRE | **Published:** 2026-11-15 | **Read Time:** 2 min read - **Summary:** Why default Ubuntu/Debian kernel settings drop TCP SYN packets above 4,096 connections, and the exact sysctl and ulimit parameters we tune for high-concurrency gateways. ## When the Linux Kernel Drops Traffic Before Your Application Sees It We often see teams spend weeks optimizing Go or Rust application handlers, only to watch load tests fail at 5,000 concurrent connections with **connect: resource temporarily unavailable** or **nf_conntrack: table full, dropping packet** in **dmesg**. Before running high-concurrency WebSocket servers or reverse proxies (**Caddy**, **NGINX**, **Traefik**, **Axum**), three Linux kernel subsystems must be tuned. --- ## 1. File Descriptors and Listen Queue Backlogs In Linux, every open TCP socket is a file descriptor. The default per-process limit (**1024**) and listen backlog (**somaxconn = 4096**) silently truncate burst connection handshakes: ```ini # /etc/sysctl.d/99-high-concurrency.conf fs.file-max = 2097152 net.core.somaxconn = 65535 net.core.netdev_max_backlog = 65535 net.ipv4.tcp_max_syn_backlog = 65535 ``` And in the systemd service unit (or container securityContext): ```ini LimitNOFILE=1048576 ``` --- ## 2. Preventing Ephemeral Port and TIME_WAIT Exhaustion on Reverse Proxies When an ingress gateway proxies thousands of short-lived requests per second to upstream microservices or PgBouncer, each outbound connection consumes a local ephemeral port **(source_ip, source_port, dest_ip, dest_port)**. By default, Linux only allocates **28,232** ephemeral ports (**32768** to **60999**) and holds closed sockets in **TIME_WAIT** for 60 seconds: ```ini net.ipv4.ip_local_port_range = 10240 65535 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_fin_timeout = 15 net.netfilter.nf_conntrack_max = 1048576 ``` Expanding the ephemeral port range to **55,295** ports and enabling safe timestamp-verified **tcp_tw_reuse** eliminated outbound port exhaustion under sustained **15,000+ RPS** load tests. --- ### 10. Enforcing Strict Multi-Tenant Data Isolation in PostgreSQL with Row-Level Security (RLS) and Session Contexts - **Canonical URL:** https://shafiktanbir.com/blog/multi-tenant-data-isolation-postgresql-row-level-security-rls - **Category:** Database Security | **Published:** 2026-11-14 | **Read Time:** 2 min read - **Summary:** How to make cross-tenant SQL data leaks mathematically impossible by enforcing PostgreSQL Row-Level Security policies tied to transaction-scoped current_setting variables. ## Why Application-Only Tenant Filtering Is Fragile In a shared-schema multi-tenant B2B SaaS, every table has a **tenant_id** column. Even with code review and integration tests, a single complex analytics query or newly added JOIN that omits **AND tenant_id = $1** can leak confidential records across tenants. By enabling **PostgreSQL Row-Level Security (RLS)**, the database kernel itself rejects or filters out any row that does not match the active request's tenant context, even if the application runs an unqualified **SELECT * FROM invoices**. --- ## 1. Enabling Row-Level Security Policies on Tenant Tables ```sql ALTER TABLE clinical_patients ENABLE ROW LEVEL SECURITY; ALTER TABLE clinical_patients FORCE ROW LEVEL SECURITY; CREATE POLICY tenant_isolation_policy ON clinical_patients USING (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid) WITH CHECK (tenant_id = NULLIF(current_setting('app.current_tenant_id', true), '')::uuid); ``` Notice two crucial details: 1. **FORCE ROW LEVEL SECURITY:** Ensures the policy applies even to the table owner role (we also run the application under a dedicated non-superuser role **app_rw**). 2. **Fail-Closed Default (**NULLIF(..., '')::uuid**):** If a developer forgets to set **app.current_tenant_id** on a connection, **current_setting** returns **NULL**, and the query safely returns **0 rows** instead of failing open. --- ## 2. Making RLS Safe with PgBouncer Transaction Pooling (**SET LOCAL**) Never use session-level **SET app.current_tenant_id = '...'** when using PgBouncer in transaction pooling mode, or the setting could leak to the next transaction reusing that backend connection. Instead, always use **SET LOCAL** (or **set_config('app.current_tenant_id', $1, true)**) inside the transaction block so PostgreSQL automatically clears the variable the moment the transaction commits or rolls back. --- ### 11. Transactional Outbox Pattern in Go and PostgreSQL: Publishing Domain Events Without Dual-Write Race Conditions - **Canonical URL:** https://shafiktanbir.com/blog/transactional-outbox-pattern-go-postgresql-zero-dual-write-bugs - **Category:** Distributed Systems | **Published:** 2026-11-13 | **Read Time:** 2 min read - **Summary:** Why committing to PostgreSQL and publishing to RabbitMQ/Kafka in the same HTTP handler loses events on crash, and how to build a SKIP LOCKED transactional outbox relay in Go. ## The Dual-Write Trap Between SQL Databases and Message Brokers Consider this common pattern in an order service: 1. **tx.Commit()** writes the new order to PostgreSQL. 2. **broker.Publish("order.created", payload)** sends the event to RabbitMQ or Kafka. If the container is OOM-killed, redeployed, or loses its TCP connection to RabbitMQ milliseconds after step 1 succeeds, the order is permanently committed in PostgreSQL, but the **order.created** event is never published. Reversing the order (publishing to RabbitMQ before committing SQL) is even worse: if **tx.Commit()** fails on a constraint violation, downstream services process a phantom order that does not exist in the database. --- ## 1. Atomic Single-Database Commit via the Outbox Table The **Transactional Outbox Pattern** solves this without slow two-phase distributed commits (2PC). Inside the exact same PostgreSQL transaction that inserts the business record, we insert the serialized event into an **outbox_events** table: ```sql BEGIN; INSERT INTO orders (id, tenant_id, amount_cents, status) VALUES ($1, $2, $3, 'PAID'); INSERT INTO outbox_events (id, aggregate_type, aggregate_id, event_type, payload, status) VALUES ($4, 'order', $1, 'order.paid.v1', $5::jsonb, 'PENDING'); COMMIT; ``` Either both rows commit atomically, or neither does. --- ## 2. Concurrent Outbox Relay Worker with FOR UPDATE SKIP LOCKED A lightweight background worker pool in Go polls pending outbox rows using **SELECT ... FOR UPDATE SKIP LOCKED** so multiple Kubernetes pod replicas can drain the outbox concurrently without ever locking each other or publishing the same row twice: ```sql WITH locked_batch AS ( SELECT id, event_type, payload FROM outbox_events WHERE status = 'PENDING' ORDER BY created_at ASC LIMIT 100 FOR UPDATE SKIP LOCKED ) UPDATE outbox_events o SET status = 'PROCESSING', locked_at = NOW() FROM locked_batch lb WHERE o.id = lb.id RETURNING o.id, o.event_type, o.payload; ``` --- ### 12. PostgreSQL Partitioning at Scale: Declarative Range Partitioning and pg_partman for Multi-TB Audit Logs - **Canonical URL:** https://shafiktanbir.com/blog/postgresql-declarative-range-partitioning-pg-partman-multi-tb-tables - **Category:** Database & Performance | **Published:** 2026-11-12 | **Read Time:** 2 min read - **Summary:** Why DELETE FROM on a 600-million-row table locks PostgreSQL with autovacuum bloat, and how monthly declarative range partitioning turns retention cleanup into a 4ms metadata drop. ## Why Bulk DELETE Statements Paralyze Large PostgreSQL Tables In PostgreSQL's MVCC storage engine, **DELETE** does not immediately free disk space. Deleting 40 million expired audit log rows marks 40 million tuples as dead, writes gigabytes of WAL traffic, and forces **autovacuum** to scan the entire table and all of its B-Tree indexes. Even worse, once a single unpartitioned B-Tree index exceeds available RAM, random index insertions across UUIDs cause continuous disk page thrashing. --- ## 1. Declarative Monthly Range Partitioning By partitioning append-only tables (**audit_events**, **webhook_deliveries**, **telemetry_logs**) by **RANGE (created_at)**, each month's data and indexes live in a compact, self-contained physical table: ```sql CREATE TABLE audit_events ( id UUID NOT NULL, tenant_id UUID NOT NULL, actor_id UUID NOT NULL, action_type VARCHAR(64) NOT NULL, payload JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (created_at, id) ) PARTITION BY RANGE (created_at); CREATE TABLE audit_events_2026_11 PARTITION OF audit_events FOR VALUES FROM ('2026-11-01 00:00:00+00') TO ('2026-12-01 00:00:00+00'); CREATE INDEX idx_audit_events_2026_11_tenant ON audit_events_2026_11 (tenant_id, created_at DESC); ``` --- ## 2. Partition Pruning and Zero-Bloat Retention Drops 1. **Automatic Partition Pruning:** When a tenant queries the last 7 days of audit logs (**WHERE created_at >= NOW() - INTERVAL '7 days'**), the PostgreSQL planner completely ignores older monthly partitions and scans only the current hot partition in RAM. 2. **4-Millisecond Retention Cleanup:** Instead of running **DELETE**, archiving a 90-day-old partition uses **ALTER TABLE audit_events DETACH PARTITION audit_events_2026_07 CONCURRENTLY** followed by **DROP TABLE**, freeing gigabytes of disk space instantaneously with **zero dead tuples** and **zero autovacuum overhead**. --- ### 13. Eliminating Go Garbage Collection Spikes in High-Throughput JSON APIs with sync.Pool and Zero-Copy Streaming - **Canonical URL:** https://shafiktanbir.com/blog/eliminating-go-gc-spikes-high-throughput-json-apis-sync-pool - **Category:** Go & Systems Performance | **Published:** 2026-11-11 | **Read Time:** 2 min read - **Summary:** How we profiled heap allocations with pprof and reduced Go GC pause frequency by 68% under 12,000 RPS using pre-sized byte buffers and sync.Pool. ## Why High-Allocation Go Services Suffer P99 Latency Jitter Go's concurrent garbage collector keeps pause times low, but it is not free. When an API endpoint allocates megabytes of short-lived heap objects per second (via **json.Marshal**, **fmt.Sprintf**, or growing slices without capacity hints), the Go runtime spends up to **30% of CPU cycles** running background GC mark workers and write barriers. Using **go tool pprof** (**alloc_space** and **inuse_space**) alongside compiler escape analysis (**go build -gcflags="-m"**), we eliminated 68% of heap allocations on our hot JSON serialization path. --- ## 1. Bounded Buffer Recycling with sync.Pool When encoding JSON responses directly into **json.Marshal(payload)**, Go allocates a fresh **[]byte** slice on every request. Instead, we stream JSON directly into a reusable ***bytes.Buffer** leased from a **sync.Pool**: ```go package bufferpool import ( "bytes" "sync" ) const maxPooledBufferCap = 64 * 1024 // 64 KB guard against pinning huge buffers var jsonBufferPool = sync.Pool{ New: func() any { return bytes.NewBuffer(make([]byte, 0, 4096)) }, } func AcquireBuffer() *bytes.Buffer { buf := jsonBufferPool.Get().(*bytes.Buffer) buf.Reset() return buf } func ReleaseBuffer(buf *bytes.Buffer) { if buf.Cap() <= maxPooledBufferCap { jsonBufferPool.Put(buf) } } ``` ### The Critical 64 KB Capacity Guard Notice the **if buf.Cap() <= maxPooledBufferCap** check before returning a buffer to the pool. Without that guard, a single outlier request that serializes a 10 MB export grows the buffer's underlying array to 10 MB and permanently pins that memory inside the pool. --- ## 2. Pre-Allocating Slice Capacities on Database Scans Replacing un-sized **var items []OrderItem** declarations with **items := make([]OrderItem, 0, expectedCount)** eliminated repeated slice growth copies (**runtime.growslice**), dropping P99 latency from **48ms to 9.4ms** at 12,000 RPS. --- ### 14. Why Building and Exiting My Own Micro-SaaS Changed How I Architect Production Backend Systems - **Canonical URL:** https://shafiktanbir.com/blog/why-building-exiting-micro-saas-changed-how-i-architect-backends - **Category:** Engineering Leadership | **Published:** 2026-11-10 | **Read Time:** 2 min read - **Summary:** How paying your own cloud bills and supporting real customers shifts engineering priorities from over-engineered abstractions to tail latency, cost discipline, and zero-downtime safety. ## From Clever Abstractions to Production Accountability Early in a software engineer's career, it is easy to fall in love with complexity for its own sake: splitting a four-person team's codebase into 18 microservices, adding three layers of generic repository interfaces, or over-provisioning cloud clusters because someone else pays the AWS invoice. Building, scaling, and exiting my own micro-SaaS venture forced an immediate mindset shift. When every dollar of wasted EC2 compute comes out of your margin and every 2 AM database lock timeout costs you a real customer, you judge architecture by three strict metrics. --- ## 1. Tail Latency and Correctness Under Contention Users do not care how clean your folder structure looks if clicking "Checkout" during a flash sale double-charges their card or hangs for 6 seconds. Whether we used **28 lines of Go + Redis Lua (EVALSHA)** to hit **0.00% double-booking across 10,000 concurrent requests**, or **Rust + Axum + SQLx FOR UPDATE locking** to sustain **8,420 RPS at 3.82ms P95 latency**, the rule is the same: keep lock scopes tiny, deterministic, and verifiable under automated race detectors. --- ## 2. Infrastructure Cost Is a First-Class Engineering Metric A system that scales traffic 2x by scaling cloud bills 4x is an architectural bug. At Cansoft Technologies, auditing 14 days of Prometheus P99 usage against bloated Helm CPU/RAM requests allowed us to cut **AWS EC2 compute costs by 35%** without changing a single line of business logic. Similarly, adding partial composite B-Tree indexes and PgBouncer transaction pooling dropped PostgreSQL P95 latency from **4.2s to 14ms** without upgrading RDS hardware. --- ## 3. Boring, Reversible Deployments and Migrations High-velocity teams ship fast because their recovery path is automated. By combining **Ansible + ArgoCD GitOps**, **3-tier RabbitMQ Dead-Letter Exchanges**, and **keyset-streamed PostgreSQL TOAST migrations with SHA-256 verification**, we made production releases predictable and boring. --- ### 15. PostgreSQL Read Replicas Without Stale-Read Bugs: Causal Consistency with LSN Tracking - **Canonical URL:** https://shafiktanbir.com/blog/postgresql-read-replicas-causal-consistency-lsn-tracking - **Category:** Database Engineering | **Published:** 2026-11-09 | **Read Time:** 2 min read - **Summary:** How to scale read-heavy PostgreSQL workloads across streaming read replicas while preventing read-your-own-write bugs using pg_current_wal_lsn() session tokens. ## The Classic Read-After-Write Bug on Asynchronous Replicas When you split database traffic so **INSERT / UPDATE / DELETE** queries hit the PostgreSQL primary and **SELECT** queries hit asynchronous streaming read replicas, you immediately run into **replication lag**. Even a healthy 80-millisecond WAL replay delay is enough to break user flows: a user submits a form (**POST /api/orders**), your frontend immediately redirects to **GET /api/orders/123** on a read replica, and the replica returns **404 Not Found** because that WAL segment has not replayed yet. --- ## 1. Tracking Write Causal Position with pg_current_wal_lsn() PostgreSQL tracks every state mutation using a monotonically increasing **Log Sequence Number (LSN)**. Whenever a user performs a write on the primary node, we query **SELECT pg_current_wal_lsn()** inside the commit response and attach that LSN value (**0/16B3748**) to a short-lived HTTP-only session header or Redis key for that user (**user:min_lsn:**, TTL 5 seconds). --- ## 2. LSN-Aware Read Replica Routing Middleware When a subsequent **GET** request arrives for that user, our database router compares the user's required minimum LSN against the replica's last replayed WAL position (**pg_last_wal_replay_lsn()**): ```go func (r *DBRouter) PickReadPool(ctx context.Context, userMinLSN string) *pgxpool.Pool { if userMinLSN == "" { return r.replicaPool } if r.replicaHasCaughtUp(userMinLSN) { return r.replicaPool } // Replica is still behind this user's last write; route safely to Primary return r.primaryPool } ``` By polling **SELECT pg_last_wal_replay_lsn()** on each replica once every 100ms in a background ticker, individual read queries never pay an extra SQL round-trip. Over **98.4% of read traffic** stays on the read replicas, while recent writers enjoy **100% causal read-your-own-write consistency**. --- ### 16. Preventing Cascading Microservice Outages with Redis Circuit Breakers and Token-Bucket Rate Limiting - **Canonical URL:** https://shafiktanbir.com/blog/preventing-cascading-microservice-outages-circuit-breakers-rate-limiting - **Category:** Distributed Systems | **Published:** 2026-11-08 | **Read Time:** 2 min read - **Summary:** How a single slow downstream dependency can exhaust thread pools across an entire API gateway, and how we isolated failure domains using distributed Redis circuit breakers. ## How One Slow Dependency Triggers a Cascading Cluster Outage Imagine your core API calls an external shipping or SMS gateway that normally responds in **120ms**. Suddenly, that provider degrades and hangs for **30 seconds** before timing out. Within seconds, every incoming request ties up a worker connection waiting on that 30-second socket. Your database connection pool saturates, memory climbs, Kubernetes liveness probes time out, and your entire API goes dark because of one non-critical downstream service. --- ## 1. Implementing a Distributed Three-State Circuit Breaker Instead of letting each pod discover downstream timeouts independently, we shared circuit state across replicas in Redis using a fast state machine (**CLOSED -> OPEN -> HALF-OPEN**): - **CLOSED (Normal):** Requests flow normally with a strict **1,500ms context deadline**. Failures increment a rolling 10-second counter. - **OPEN (Tripped):** If the failure rate exceeds **25%** across at least 20 requests in 10 seconds, the circuit trips **OPEN** for 15 seconds. All calls fail fast in **0.2ms** (or queue asynchronously to RabbitMQ) without opening a network socket. - **HALF-OPEN (Probe):** After 15 seconds, a single probe request is allowed through. If it succeeds, the circuit closes; if it fails, the circuit stays open for another 15 seconds. ```go func (cb *CircuitBreaker) Execute(ctx context.Context, key string, fn func(context.Context) error) error { state, err := cb.getState(ctx, key) if err == nil && state == StateOpen { return ErrCircuitOpenFastFail } callCtx, cancel := context.WithTimeout(ctx, 1500*time.Millisecond) defer cancel() err = fn(callCtx) if err != nil { cb.recordFailure(ctx, key) return err } cb.recordSuccess(ctx, key) return nil } ``` --- ## 2. Per-Tenant Noisy-Neighbor Isolation via Token Buckets In a multi-tenant SaaS, a single customer running an unthrottled bulk import script can starve other tenants. We added an atomic Redis Lua **token-bucket rate limiter** keyed by **tenant_id** at the API gateway so noisy tenants receive clean **HTTP 429 Retry-After** headers while every other tenant experiences flat sub-20ms latency. --- ### 17. Guaranteeing Database Persistence on Kubernetes: StatefulSets, PVCs, and Safe Node Drain Strategies - **Canonical URL:** https://shafiktanbir.com/blog/guaranteeing-database-persistence-kubernetes-statefulsets-pvcs - **Category:** Kubernetes Architecture | **Published:** 2026-11-07 | **Read Time:** 2 min read - **Summary:** How to run stateful PostgreSQL and Redis workloads safely on Kubernetes using StatefulSets, Retain storage classes, PodDisruptionBudgets, and automated WAL archiving. ## Why Stateless Deployments Corrupt Stateful Workloads A standard Kubernetes **Deployment** treats pods as interchangeable cattle. During a rolling update or node drain, Kubernetes can spin up a new pod before the old pod has cleanly flushed its write-ahead log (WAL) to disk, or delete a dynamically provisioned volume if a PersistentVolumeClaim (PVC) is accidentally removed. When running stateful **PostgreSQL** and **Redis** clusters on Kubernetes, four architectural safeguards are mandatory. --- ## 1. Custom StorageClass with reclaimPolicy: Retain and WaitForFirstConsumer The default Kubernetes **StorageClass** in most cloud providers sets **reclaimPolicy: Delete**. If a Helm chart uninstall or operator bug deletes the PVC, the underlying block storage volume is permanently wiped. We always define a dedicated **StorageClass** for stateful data with **reclaimPolicy: Retain** and **volumeBindingMode: WaitForFirstConsumer** (ensuring the EBS/CSI volume is provisioned in the exact same Availability Zone as the scheduled pod): ```yaml apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: production-block-retain provisioner: ebs.csi.aws.com volumeBindingMode: WaitForFirstConsumer reclaimPolicy: Retain allowVolumeExpansion: true parameters: type: gp3 iops: "6000" throughput: "250" encrypted: "true" ``` --- ## 2. Protecting Quorum During Node Upgrades with PodDisruptionBudgets When draining worker nodes for Linux kernel patching (**kubectl drain**), Kubernetes will evict pods as fast as possible unless constrained by a **PodDisruptionBudget (PDB)**. For a 3-node replicated stateful cluster, we enforce **maxUnavailable: 1** so node maintenance never takes down quorum: ```yaml apiVersion: policy/v1 kind: PodDisruptionBudget metadata: name: postgres-ha-pdb spec: maxUnavailable: 1 selector: matchLabels: app: postgres-ha ``` Combined with continuous **WAL-G** streaming to encrypted S3 object storage, our recovery point objective (RPO) stays under **10 seconds** even in a complete availability zone failure. --- ### 18. Stopping Alert Fatigue: How We Rebuilt Our Observability Stack with Prometheus, Grafana, and Loki - **Canonical URL:** https://shafiktanbir.com/blog/stopping-alert-fatigue-observability-prometheus-grafana-loki - **Category:** Observability & SRE | **Published:** 2026-11-06 | **Read Time:** 2 min read - **Summary:** Why paging engineers on raw CPU spikes causes alert fatigue, and how we shifted to symptom-based SLO alerting and trace-correlated Loki structured logs. ## Why Paging on Raw CPU Spikes Destroys On-Call Engineers In many growing backend teams, the #alerts channel fires 40 to 60 times a day: *"Node 3 CPU > 80% for 2 minutes"*, *"Pod memory > 75%"*, *"Disk I/O spike"*. Because 95% of those alerts resolve themselves when a background job finishes, engineers mentally mute the channel - until a real database deadlock silently drops checkout traffic for 25 minutes. When we overhauled our observability stack using **Prometheus**, **Grafana**, **Loki**, and **Alertmanager**, we enforced a simple rule: **never page a human unless user-facing SLOs are degrading or capacity will exhaust within 4 hours**. --- ## 1. Alerting on Multi-Window Error Budget Burn Rates A 90-second CPU spike during a nightly report job is not an incident. A sustained rise in HTTP 5xx responses or P95 latency above 500ms is. We replaced noisy threshold alerts with **Prometheus symptom alerts** that only fire when both short-window (**5m**) and medium-window (**30m**) error rates breach our SLO threshold: ```yaml groups: - name: slo-api-availability rules: - alert: HighApi5xxErrorRateBurn expr: | ( sum(rate(http_requests_total{status=~"5..", job="core-api"}[5m])) / sum(rate(http_requests_total{job="core-api"}[5m])) ) > 0.01 and ( sum(rate(http_requests_total{status=~"5..", job="core-api"}[30m])) / sum(rate(http_requests_total{job="core-api"}[30m])) ) > 0.005 for: 3m labels: severity: critical annotations: summary: "Core API 5xx error rate exceeds 1% SLO burn" runbook_url: "https://shafiktanbir.com/?tab=blog" ``` --- ## 2. Correlating Metrics to Structured Loki Logs via Trace IDs Metrics tell you *what* broke; structured logs tell you *why* and for *which tenant*. Every incoming HTTP request receives a **X-Request-ID / trace_id** middleware header injected into every structured JSON log line (**zerolog** in Go / **tracing** in Rust) and Prometheus exemplar. When an alert fires, the on-call engineer clicks the spike in Grafana and jumps directly to the exact Loki log stream for that failing request in under 10 seconds. --- ### 19. Building a Zero-Trust Multi-Cloud Mesh Network with Self-Hosted Headscale WireGuard and Caddy - **Canonical URL:** https://shafiktanbir.com/blog/zero-trust-multi-cloud-mesh-network-headscale-wireguard-caddy - **Category:** Cloud Networking | **Published:** 2026-11-05 | **Read Time:** 2 min read - **Summary:** How we connected distributed cloud VPS nodes and private databases across regions without exposing public ports using self-hosted Headscale WireGuard VPN and mTLS Caddy proxies. ## Why Publicly Exposed Infrastructure Ports Fail Security Audits When engineering teams run hybrid workloads across multiple cloud providers (for example, AWS EC2 application nodes communicating with dedicated bare-metal database or observability nodes), networking quickly becomes messy. Opening ports **5432 (PostgreSQL)**, **6379 (Redis)**, or **9090 (Prometheus)** to public IPv4 interfaces with brittle firewall whitelists invites brute-force scans and misconfiguration leaks. To unify our distributed Linux nodes into a single encrypted private LAN without per-user SaaS VPN licensing fees, we deployed a **self-hosted Headscale control plane** managing **kernel-space WireGuard** tunnels. --- ## 1. Self-Hosted Headscale Control Plane + Kernel WireGuard Data Plane **Headscale** is an open-source, self-hosted implementation of the Tailscale control server. Importantly, the Headscale server **never touches application traffic**: - **Control Plane (Headscale + Caddy TLS):** Exchanges public WireGuard keys, assigns deterministic **100.64.0.x** CGNAT private mesh IPs, and distributes ACL firewall policies. - **Data Plane (Peer-to-Peer Kernel WireGuard):** Encrypted UDP packets flow directly point-to-point between nodes using ChaCha20-Poly1305 encryption in the Linux kernel with sub-millisecond overhead. --- ## 2. Enforcing Least-Privilege Mesh ACLs (HuJSON) Joining the WireGuard mesh does not grant blanket network access. Headscale enforces strict tag-based **Access Control Lists (ACLs)** at the packet filter level on every node: ```json { "tagOwners": { "tag:k3s-worker": ["autogroup:admin"], "tag:db-primary": ["autogroup:admin"], "tag:monitoring": ["autogroup:admin"] }, "acls": [ { "action": "accept", "src": ["tag:k3s-worker"], "dst": ["tag:db-primary:5432", "tag:db-primary:6379"] }, { "action": "accept", "src": ["tag:monitoring"], "dst": ["tag:k3s-worker:9100", "tag:db-primary:9187"] } ] } ``` With this policy active, application workers can reach PostgreSQL (**5432**) and Redis (**6379**) on the database node, but cannot SSH (**22**) into the database node, and public internet scanners see **zero open ports** on **eth0**. --- ### 20. Hardening Multi-Tenant Kubernetes Clusters for HIPAA and PIPEDA: Default-Deny NetworkPolicies and RBAC - **Canonical URL:** https://shafiktanbir.com/blog/hardening-multi-tenant-kubernetes-hipaa-pipeda-networkpolicies-rbac - **Category:** Cloud Security | **Published:** 2026-11-04 | **Read Time:** 2 min read - **Summary:** How we locked down lateral pod-to-pod movement in Kubernetes using default-deny NetworkPolicies, least-privilege ServiceAccount RBAC, and Trivy CI container gates. ## Kubernetes Is Flat by Default (And Why That Breaks Compliance) Out of the box, Kubernetes networking is completely flat. Unless you explicitly install a CNI policy engine and define **NetworkPolicy** resources, a compromised frontend pod in a staging namespace can open a direct TCP connection to a production Redis or PostgreSQL pod in another namespace. When preparing our multi-tenant healthcare infrastructure (**emmai.ca**) for enterprise security reviews and HIPAA/PIPEDA compliance, we implemented a **Zero-Trust Kubernetes hardening baseline**. --- ## 1. Enforcing Default-Deny Ingress and Egress NetworkPolicies The first rule deployed to every production namespace is a **default-deny-all** policy that drops all pod-to-pod traffic unless explicitly whitelisted: ```yaml apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: default-deny-all namespace: emmai-prod spec: podSelector: {} policyTypes: - Ingress - Egress ``` Once default-deny is active, we grant narrow, port-specific allow rules. For example, only pods labeled **app: emmai-core-api** are permitted to open port **5432** to PgBouncer, and only the ingress controller namespace can reach port **8080** on the API pods. --- ## 2. Disabling Auto-Mounted ServiceAccount Tokens By default, Kubernetes mounts a bearer token at **/var/run/secrets/kubernetes.io/serviceaccount/token** inside every container. If an application suffers a Server-Side Request Forgery (SSRF) or local file inclusion bug, an attacker can read that token and query the Kubernetes API server. We disabled automatic token mounting on all application pods that do not talk to the Kubernetes API: ```yaml apiVersion: v1 kind: ServiceAccount metadata: name: emmai-stateless-api-sa namespace: emmai-prod automountServiceAccountToken: false ``` --- ## 3. Blocking Critical CVEs in GitHub Actions with Trivy Security scanning in production is too late. We added **Trivy** image scanning directly inside our GitHub Actions build workflow with **--exit-code 1 --severity CRITICAL,HIGH --ignore-unfixed**, ensuring vulnerable base images fail the PR build before ArgoCD ever sees them. --- ### 21. Scaling Production RAG Pipelines: Hybrid Vector Search, Tenant Isolation, and LLM Fallback Routing - **Canonical URL:** https://shafiktanbir.com/blog/scaling-production-rag-pipelines-hybrid-vector-search-llm-fallback - **Category:** AI Infrastructure | **Published:** 2026-11-03 | **Read Time:** 2 min read - **Summary:** Why prototype RAG demos fail in production and how we built hybrid BM25 + dense vector retrieval, strict multi-tenant metadata filtering, and automatic LLM failover in FastAPI. ## Why 90% of Prototype RAG Pipelines Fail in Production A basic Retrieval-Augmented Generation (RAG) tutorial embeds chunks into a vector database, runs cosine similarity, and sends the top 5 chunks to a single OpenAI endpoint. In production B2B and healthcare SaaS (**emmai.ca**), that naive pipeline breaks in three ways: 1. **Pure Cosine Similarity Misses Exact Identifiers:** Dense embeddings are great for semantic concepts, but terrible at matching exact medical ICD-10 codes, drug dosages, or part numbers. 2. **Cross-Tenant Context Leakage:** Filtering tenant permissions *after* vector retrieval risks exposing another customer's document chunks if the top-K filter is misconfigured. 3. **Upstream LLM Rate Limits and HTTP 529 Brownouts:** Relying on a single model endpoint causes user-facing timeouts whenever the provider experiences regional capacity spikes. --- ## 1. Hybrid Retrieval: Reciprocal Rank Fusion (Dense + BM25 Sparse) To capture both semantic meaning and exact clinical/technical terminology, we combined **dense embeddings** with **sparse BM25 keyword matching** and merged the results using **Reciprocal Rank Fusion (RRF)**: ```python from typing import List, Dict def reciprocal_rank_fusion( dense_hits: List[str], sparse_hits: List[str], k: int = 60, ) -> List[str]: scores: Dict[str, float] = {} for rank, doc_id in enumerate(dense_hits, start=1): scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank) for rank, doc_id in enumerate(sparse_hits, start=1): scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank) return sorted(scores.keys(), key=lambda d: scores[d], reverse=True) ``` --- ## 2. Hard Pre-Filtering by Tenant ID at the Vector Index Layer In a multi-tenant system, security boundaries must be enforced inside the vector index query itself, never in application memory after retrieval: ```python vector_results = await vector_index.query( vector=query_embedding, top_k=12, filter={ "tenant_id": {"$eq": authenticated_tenant_id}, "document_status": {"$eq": "ACTIVE"}, }, include_metadata=True, ) ``` --- ## 3. Deterministic LLM Circuit Breaking and Provider Failover We wrapped our FastAPI completion client in a **3.5-second time-to-first-token (TTFT) deadline** with automatic fallback routing across primary and secondary model providers. When the primary LLM returns HTTP 429 or exceeds the 3.5s TTFT threshold, the router transparently switches to the fallback provider, maintaining **99.94% RAG endpoint availability**. --- ### 22. Eliminating Production Server Drift with Ansible Bare-Metal Provisioning and ArgoCD GitOps - **Canonical URL:** https://shafiktanbir.com/blog/eliminating-production-server-drift-ansible-argocd-gitops - **Category:** DevOps & GitOps | **Published:** 2026-11-02 | **Read Time:** 2 min read - **Summary:** How we replaced manual SSH hotfixes with deterministic Ansible node playbooks, modular Helm charts, and ArgoCD pull-based GitOps synchronization across multi-node K3s clusters. ## Why Manual SSH Changes Destroy Cluster Reliability Every undocumented **kubectl edit** or manual SSH config tweak on a production Linux node creates a ticking time bomb. Two weeks later, when a worker node is replaced or a pod restarts, the hotfix vanishes and triggers an incident that nobody can reproduce in staging. When I took ownership of cloud infrastructure at Cansoft Technologies, we enforced a strict rule: **zero human SSH mutations in production**. Every OS kernel parameter, K3s node binary, and Kubernetes workload must be reconciled from Git. --- ## 1. Layer 1: Deterministic Node Provisioning with Ansible Before Kubernetes even starts, underlying Linux worker nodes need identical sysctl networking limits, WireGuard mesh interfaces, and containerd log rotation rules. We codified node bootstrapping into idempotent **Ansible** roles: ```yaml - name: Harden Linux Kernel & Sysctl for High-Concurrency K3s Nodes hosts: k3s_cluster become: true tasks: - name: Configure sysctl network & file descriptor bounds ansible.posix.sysctl: name: "{{ item.key }}" value: "{{ item.value }}" state: present reload: true loop: - { key: "net.core.somaxconn", value: "32768" } - { key: "net.ipv4.ip_local_port_range", value: "1024 65000" } - { key: "fs.file-max", value: "2097152" } - { key: "vm.max_map_count", value: "262144" } ``` --- ## 2. Layer 2: Pull-Based GitOps with ArgoCD and Helm In traditional push-based CI pipelines, GitHub Actions holds cluster-admin credentials and runs **helm upgrade** directly. If a manual change happens inside the cluster afterward, CI has no idea the cluster drifted. With **ArgoCD** running inside the cluster: 1. CI builds the container image, runs Trivy security scans, and commits the new immutable image SHA digest to our GitOps repository. 2. ArgoCD detects the Git commit within seconds and reconciles the live Kubernetes state to match Git. 3. **Self-Heal Enabled (**selfHeal: true**):** If anyone manually edits a Service or Deployment in the cluster, ArgoCD immediately overwrites the manual edit back to the Git state. ```yaml apiVersion: argoproj.io/v1alpha1 kind: Application metadata: name: emmai-core-api namespace: argocd spec: project: production source: repoURL: https://github.com/org/infra-gitops.git targetRevision: main path: charts/emmai-core-api helm: valueFiles: - values-prod.yaml destination: server: https://kubernetes.default.svc namespace: emmai-prod syncPolicy: automated: prune: true selfHeal: true ``` --- ## 3. Zero-Downtime Rolling Updates with Readiness Gates By combining **maxUnavailable: 0**, **maxSurge: 1**, and strict HTTP **/healthz/ready** database-ping probes, a broken container image never receives live ingress traffic and halts the rollout automatically before affecting active users. --- ### 23. How We Cut Real-Time GPS Transit API Latency by 45% on Colorado's Statewide Bus Network (ridebustang.com) - **Canonical URL:** https://shafiktanbir.com/blog/real-time-gps-transit-api-latency-redis-postgresql-ridebustang - **Category:** Backend Performance | **Published:** 2026-11-01 | **Read Time:** 2 min read - **Summary:** Decoupling GTFS-Realtime vehicle telemetry streams from relational PostgreSQL queries using Redis read-through caching and composite index tuning for ridebustang.com. ## When Commuter Polling Collides with Live GPS Telemetry On a statewide public transit network like **ridebustang.com** (serving Colorado's intercity bus corridors along I-25 and I-70), traffic patterns are spiky. During morning rush hour and winter snowstorms, thousands of riders open the mobile app simultaneously to check live bus ETAs and seat availability. Initially, every route status request joined static schedule tables with recently ingested **GTFS-Realtime** vehicle coordinates directly inside PostgreSQL. Under peak commuter load, database read IOPS spiked and P95 API latency climbed past **1.8 seconds**. Here is the three-part architecture change that reduced P95 API response latency by **45%**. --- ## 1. Separating Ephemeral GPS Telemetry from Relational State A vehicle's GPS coordinate updates every 3 to 5 seconds. Writing and querying ephemeral coordinates inside heavy relational SQL joins creates unnecessary WAL churn and buffer eviction. We split the data path into two distinct storage tiers: - **In-Memory Redis Geo & Hash State:** Incoming GTFS-Realtime vehicle positions are written directly to Redis keys (**transit:vehicle:**) with a **15-second TTL** and broadcast to connected clients over WebSockets. - **PostgreSQL for Durable Ticketing & Schedules:** PostgreSQL handles only transactional ticket purchases, rider accounts, and timetable versions. ```typescript export async function getRouteLiveStatus(routeId: string) { const cacheKey = `transit:route:status:${routeId}`; const cached = await redis.get(cacheKey); if (cached) { return JSON.parse(cached); } const [schedule, liveVehicles] = await Promise.all([ db.query( `SELECT stop_id, arrival_time, sequence_no FROM route_stops WHERE route_id = $1 AND active = true ORDER BY sequence_no ASC`, [routeId] ), redis.hgetall(`transit:vehicles:route:${routeId}`), ]); const payload = mergeScheduleWithTelemetry(schedule.rows, liveVehicles); await redis.set(cacheKey, JSON.stringify(payload), "EX", 5); return payload; } ``` --- ## 2. Eliminating N+1 ORM Queries on Multi-Stop Route Timetables Our second bottleneck came from an ORM relation loader that executed a separate SQL query for each bus stop along a 28-stop corridor (**1 + 28** round-trips per request). We replaced the nested ORM relation calls with a single composite-indexed SQL query using PostgreSQL **jsonb_agg** so the entire route timetable returned in a single network round-trip in under **4.2ms**. --- ## 3. Stampede Protection with Single-Flight Cache Refresh With a 5-second TTL on hot route keys, 500 concurrent requests arriving at second 6 could all miss the cache simultaneously and hammer PostgreSQL. We wrapped the cache-miss loader in an in-memory **single-flight promise coalescer** so only 1 query hits PostgreSQL per route every 5 seconds while the other 499 requests share the resolved payload. --- ### 24. How We Cut AWS EC2 Compute Bills by 35% with K3s Pod Request Tuning and Kyverno Admission Policies - **Canonical URL:** https://shafiktanbir.com/blog/cut-aws-ec2-compute-bills-35-percent-k3s-pod-request-tuning - **Category:** Cloud Infrastructure | **Published:** 2026-10-31 | **Read Time:** 3 min read - **Summary:** How we audited 14 days of Prometheus P99 resource metrics against bloated Helm CPU/RAM requests and enforced Kyverno CI policies to reduce monthly AWS EC2 node costs by 35%. ## The Hidden Tax of Copy-Pasted Kubernetes Resource Requests When a Kubernetes cluster keeps spinning up new AWS EC2 worker nodes while **actual CPU utilization sits below 22%**, the problem is almost never traffic growth. The Kubernetes scheduler (**kube-scheduler**) does not schedule pods based on real-time CPU or memory usage. It schedules pods strictly against **resources.requests**. If 30 microservices copy-paste **requests.cpu: 1000m** from a starter Helm template while only consuming **75m** at peak traffic, the scheduler marks the worker nodes as full and triggers cluster autoscaling for ghost capacity. Here is how we cut our monthly AWS EC2 compute bill by **35%** across our production **K3s** clusters at Cansoft Technologies with zero downtime. --- ## 1. Auditing 14-Day P99 Usage Against Provisioned Requests in Prometheus Before changing a single Helm chart, we ran a 14-day Prometheus query comparing the **99th percentile actual CPU usage** of every deployment against its configured CPU request: ```promql quantile_over_time( 0.99, rate(container_cpu_usage_seconds_total{container!="", image!=""}[5m])[14d:5m] ) / on (namespace, pod, container) kube_pod_container_resource_requests{resource="cpu"} ``` Over 65% of our internal stateless services were using less than **12%** of their requested CPU and less than **28%** of their requested memory. --- ## 2. Right-Sizing Requests and Tuning Horizontal Pod Autoscalers (HPA) We applied a deterministic sizing formula across every microservice: - **CPU Request:** Set to **1.25x of 14-day P95 usage** so normal traffic never throttles. - **CPU Limit:** Removed hard CPU limits on latency-sensitive API pods to avoid Linux CFS bandwidth throttling spikes when spare node cores are idle. - **Memory Request & Limit:** Set equal (**Guaranteed QoS** for stateful workers, or **1.3x P99 working set** for API pods) to eliminate unexpected OOMKills. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: billing-webhook-worker spec: template: spec: containers: - name: worker resources: requests: cpu: "120m" memory: "192Mi" limits: memory: "256Mi" --- apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: billing-webhook-worker-hpa spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: billing-webhook-worker minReplicas: 2 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 ``` --- ## 3. Preventing Regression with Kyverno Policies and CI Hygiene Checks Right-sizing once is useless if developers merge new bloated YAML manifests the following week. We added a **Kyverno ClusterPolicy** and a Go CLI check in GitHub Actions that blocks any pull request missing explicit resource bounds or requesting more than **500m CPU** without an architecture exemption label. Within 48 hours of rolling out the right-sized Helm charts via ArgoCD, we drained and terminated 35% of our EC2 worker nodes with zero latency degradation. --- ### 25. How We Cut PostgreSQL P95 Query Latency from 4.2s to 14ms Under 15,000 RPS Without Upgrading AWS RDS - **Canonical URL:** https://shafiktanbir.com/blog/postgresql-p95-latency-4200ms-to-14ms-partial-indexes-pgbouncer - **Category:** Database & Performance | **Published:** 2026-10-30 | **Read Time:** 3 min read - **Summary:** How we eliminated sequential table scans and connection pool thrashing on a multi-tenant SaaS database using partial composite B-Tree indexes and PgBouncer transaction pooling. ## Why Throwing Larger RDS Instances at Slow Queries Fails When a multi-tenant B2B SaaS database hits **98% CPU utilization** and **4.2-second P95 query latency**, the knee-jerk reaction is to scale the AWS RDS instance vertically from **db.r6g.xlarge** to **db.r6g.4xlarge**. Vertical scaling buys temporary breathing room, doubles the monthly infrastructure bill, and leaves the underlying execution bottleneck untouched. As soon as tenant data grows another 30%, CPU saturates again. Here is how we dropped PostgreSQL P95 query latency from **4.2 seconds to 14ms under 15,000 requests per second (RPS)** without upgrading the AWS RDS instance. --- ## 1. Diagnosing the Sequential Scan Trap with EXPLAIN (ANALYZE, BUFFERS) Our slowest endpoint fetched active dashboard notifications and pending tasks for a specific tenant and user role. Even though we had single-column indexes on **tenant_id** and **status**, PostgreSQL was spending 3.8 seconds reading tens of thousands of historical archived rows from disk and sorting them in memory. Running **EXPLAIN (ANALYZE, BUFFERS)** exposed two expensive operations: 1. **Bitmap Heap Scan with Recheck:** PostgreSQL combined two separate single-column indexes, read 180,000 historical pages, and filtered out 96% of them where **is_archived = true**. 2. **External Merge Disk Sort:** Because the sort column (**created_at DESC**) was not part of a composite index, PostgreSQL spilled temporary sort files to disk on every dashboard refresh. ```sql -- Before: Single-column indexes forced Bitmap Heap Scans + Disk Sort EXPLAIN (ANALYZE, BUFFERS) SELECT id, title, priority, created_at FROM tenant_tasks WHERE tenant_id = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' AND status = 'PENDING' AND is_archived = false ORDER BY created_at DESC LIMIT 25; ``` --- ## 2. Partial Composite Covering Indexes (CONCURRENTLY) Because 94% of rows in **tenant_tasks** were completed or archived historical records, indexing the entire table wasted gigabytes of shared buffer RAM. We replaced the single-column indexes with a **partial composite B-Tree index** built **CONCURRENTLY** so live production writes were never blocked: ```sql CREATE INDEX CONCURRENTLY idx_tenant_tasks_active_feed ON tenant_tasks (tenant_id, created_at DESC) INCLUDE (id, title, priority) WHERE status = 'PENDING' AND is_archived = false; ``` ### Why This Index Reduced Latency by 99.6% - **Partial Predicate (WHERE status = 'PENDING' AND is_archived = false):** Shrunk the index footprint by **89%**, keeping the entire active working set pinned inside PostgreSQL **shared_buffers** RAM. - **Composite Sort Match (tenant_id, created_at DESC):** PostgreSQL walks the B-Tree in exact reverse chronological order and stops immediately after reading 25 rows. - **Covering Payload (INCLUDE id, title, priority):** Enabled an **Index-Only Scan** with **0 heap fetches** on clean visibility map pages. --- ## 3. Eliminating Connection Thrash with PgBouncer Transaction Pooling At 15,000 RPS across 40 Kubernetes microservice pods, opening 800 direct PostgreSQL connections caused severe Linux kernel context-switching and lock contention on **ProcArrayLock**. We deployed **PgBouncer** in **transaction pooling mode** between the application pods and RDS: ```ini [databases] saas_prod = host=rds-primary.internal port=5432 dbname=saas_prod [pgbouncer] pool_mode = transaction max_client_conn = 4000 default_pool_size = 48 reserve_pool_size = 12 server_idle_timeout = 60 ``` By multiplexing **4,000 application connections** down to **48 active PostgreSQL backend processes**, database CPU utilization dropped from **98% to 24%**, and P95 query latency stabilized at **14ms**. --- ### 26. How We Engineered Zero-Downtime Medical Data Migration for Multi-GB PostgreSQL TOAST JSONB Records - **Canonical URL:** https://shafiktanbir.com/blog/zero-downtime-medical-data-migration-postgresql-toast-jsonb - **Category:** Database & Cloud Migration | **Published:** 2026-10-29 | **Read Time:** 4 min read - **Summary:** How we migrated multi-gigabyte clinical datasets and compressed PostgreSQL TOAST JSONB records for emmai.ca with zero clinic downtime using keyset streaming, 3-tier WAN deduplication, and SHA-256 checksum verification. ## Why Medical Record Migrations Cannot Use Maintenance Windows When migrating a live multi-clinic healthcare platform (**emmai.ca**), shutting down the database for a 6-hour weekend maintenance window is not an option. Physicians, front-desk coordinators, and automated lab integrations read and write patient charts continuously. Even worse, medical datasets are not small flat rows. A single clinic tenant holds: - Millions of historical patient encounters and SOAP clinical notes - Deeply nested **PostgreSQL JSONB** clinical documents compressed inside **TOAST** storage tables - Strict HIPAA/PIPEDA audit requirements where every single migrated record must match its cryptographic checksum before cutover When a naive migration script runs a bulk **SELECT \*** across tens of gigabytes of TOASTed JSONB columns, PostgreSQL decompresses those blobs into RAM all at once, triggering an Out-Of-Memory (OOM) kernel kill on the primary database node. Here is how we engineered a **zero-downtime, bounded-memory migration engine** that moved multi-gigabyte medical datasets without disrupting live clinic operations. --- ## 1. Keyset-Paginated Streaming Over PostgreSQL TOAST Tables Never use **OFFSET / LIMIT** when migrating millions of rows. An **OFFSET 5000000** query forces PostgreSQL to scan and discard five million rows before returning a single page, degrading migration speed exponentially over time. Instead, we used **strictly ordered keyset pagination** over the primary `(tenant_id, id)` B-Tree index with a bounded batch size of **250 TOAST records per stream chunk**: ```sql SELECT id, tenant_id, patient_id, soap_payload_jsonb, updated_at FROM clinical_encounters WHERE tenant_id = $1 AND id > $2 ORDER BY id ASC LIMIT 250; ``` By keeping each batch under 250 records and immediately streaming the transformed payload to the target cluster, worker memory usage stayed flat below **180 MB RSS** regardless of whether a clinic had 50,000 or 5,000,000 patient charts. --- ## 2. Three-Tier WAN Deduplication and Checksum Verification Medical records frequently contain repeated attachment metadata, standardized clinical templates, and duplicate historical imports. Transferring raw uncompressed JSONB payloads across a Wide Area Network (WAN) saturates bandwidth and slows cutover. We implemented a **three-tier verification and deduplication pipeline**: 1. **Canonical JSON SHA-256 Hashing:** Before transmission, the migrator computes a deterministic SHA-256 digest of the normalized JSONB document. 2. **Target State Fingerprinting:** If the target PostgreSQL cluster already holds the exact `(record_id, sha256_digest)` from an earlier pre-sync pass, the record is skipped in **O(1)** time without transferring the payload over the wire. 3. **Dual-Write Change Data Capture (CDC) Catch-Up:** While the historical backfill runs, live clinic writes are captured via an append-only audit log table and replayed idempotently until replication lag drops below **50 milliseconds**. ```python import hashlib import json from typing import Any, Dict def compute_canonical_digest(payload: Dict[str, Any]) -> str: canonical_bytes = json.dumps( payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False, ).encode("utf-8") return hashlib.sha256(canonical_bytes).hexdigest() async def sync_clinical_batch(source_conn, target_conn, tenant_id: str, last_id: str): rows = await source_conn.fetch( """ SELECT id, patient_id, soap_payload_jsonb, updated_at FROM clinical_encounters WHERE tenant_id = $1 AND id > $2 ORDER BY id ASC LIMIT 250 """, tenant_id, last_id, ) if not rows: return None records_to_upsert = [] for row in rows: digest = compute_canonical_digest(row["soap_payload_jsonb"]) records_to_upsert.append(( row["id"], tenant_id, row["patient_id"], json.dumps(row["soap_payload_jsonb"]), digest, row["updated_at"], )) await target_conn.executemany( """ INSERT INTO clinical_encounters (id, tenant_id, patient_id, soap_payload_jsonb, payload_sha256, updated_at) VALUES ($1, $2, $3, $4::jsonb, $5, $6) ON CONFLICT (id) DO UPDATE SET soap_payload_jsonb = EXCLUDED.soap_payload_jsonb, payload_sha256 = EXCLUDED.payload_sha256, updated_at = EXCLUDED.updated_at WHERE clinical_encounters.payload_sha256 IS DISTINCT FROM EXCLUDED.payload_sha256 """, records_to_upsert, ) return rows[-1]["id"] ``` Notice the critical clause on the final line: **WHERE clinical_encounters.payload_sha256 IS DISTINCT FROM EXCLUDED.payload_sha256**. If a row has not changed since the pre-migration sync, PostgreSQL does not write a dead tuple or bloat the WAL log. --- ## 3. Atomic Tenant Cutover with Instant Rollback Safety Rather than flipping DNS for the entire platform at once, we migrated and cut over **one clinic tenant at a time**: 1. Run the background keyset backfill while the clinic works normally on the legacy database. 2. Run the automated SHA-256 row-count and checksum verifier across 100% of the tenant's records. 3. Briefly pause writes for that single tenant (**under 800ms**), replay the final delta rows, and flip the tenant routing flag in Redis to point to the new PostgreSQL cluster. --- ## Production Results on emmai.ca - **Scheduled Downtime Required:** Zero minutes across all clinic cutovers - **Data Integrity:** 100.00% SHA-256 checksum match across millions of clinical SOAP notes and JSONB attachments - **Primary Database Stability:** Zero OOM incidents and less than 8% additional CPU overhead during daytime backfill runs. --- ### 27. Zero-Message-Loss Webhook Processing with RabbitMQ Dead-Letter Exchanges (10s -> 60s -> Poison Queue) - **Canonical URL:** https://shafiktanbir.com/blog/rabbitmq-dlx-zero-message-loss-webhook-pipeline-go - **Category:** Distributed Systems & Messaging | **Published:** 2026-10-28 | **Read Time:** 4 min read - **Summary:** How we eliminated dropped payment webhooks and head-of-line queue blocking by building a 3-tier RabbitMQ Dead-Letter Exchange (DLX) retry pipeline (10s -> 60s -> Poison Queue) in Go with PostgreSQL idempotency guards. ## Why Naive Webhook Consumers Lose Revenue Events Third-party payment and fulfillment webhooks rarely fail cleanly. Downstream databases experience brief lock spikes, external verification APIs return transient HTTP 502 responses, or a malformed payload triggers an unhandled parser error. If your webhook consumer processes events synchronously or uses a single RabbitMQ queue with immediate re-queueing (**basic.nack(requeue=true)**), two failure modes happen in production: 1. **Infinite hot-loop storms:** A single malformed payload is rejected and immediately re-queued at the head of the line, pegging CPU at 100% and blocking thousands of valid webhooks behind it. 2. **Silent message drops:** If a consumer drops the message after one failed attempt without durable retry routing, critical payment confirmation events vanish permanently. To guarantee **zero message loss** without blocking real-time traffic, we built a **three-stage Dead-Letter Exchange (DLX) retry pipeline** in **RabbitMQ** and **Go** with deterministic exponential tiers (**10s -> 60s -> Poison Queue**). --- ## 1. The Three-Tier RabbitMQ Topology Instead of sleeping inside worker goroutines (which ties up prefetch slots and blocks concurrency), we let RabbitMQ handle time-delayed retries natively using **per-queue message TTLs** and **Dead-Letter Exchanges**: - **Primary Work Queue (webhooks.process.q):** Receives live incoming webhook events immediately. If processing fails with a transient error, the worker rejects the message (`requeue=false`), routing it to the Retry Exchange. - **Tier 1 Retry Queue (webhooks.retry.10s.q):** Holds the failed message for **10,000ms (10s)** with zero active consumers. When the TTL expires, RabbitMQ automatically dead-letters the message back to the Primary Work Queue. - **Tier 2 Retry Queue (webhooks.retry.60s.q):** If the message fails a second time, the worker routes it to the **60,000ms (60s)** delay queue before re-entering the Primary Work Queue. - **Tier 3 Poison Queue (webhooks.dlq.poison.q):** If the message fails after the 60-second tier (or fails initial schema validation), it is routed permanently to the Poison Queue for inspection and one-click replay. ```go package messaging import amqp "github.com/rabbitmq/amqp091-go" func DeclareWebhookTopology(ch *amqp.Channel) error { if err := ch.ExchangeDeclare("webhooks.direct", "direct", true, false, false, false, nil); err != nil { return err } if err := ch.ExchangeDeclare("webhooks.dlx", "direct", true, false, false, false, nil); err != nil { return err } // Tier 1: 10-second delay queue that routes back to webhooks.direct on expiry _, err := ch.QueueDeclare("webhooks.retry.10s.q", true, false, false, false, amqp.Table{ "x-message-ttl": int32(10000), "x-dead-letter-exchange": "webhooks.direct", "x-dead-letter-routing-key": "webhooks.process", }) if err != nil { return err } // Tier 2: 60-second delay queue that routes back to webhooks.direct on expiry _, err = ch.QueueDeclare("webhooks.retry.60s.q", true, false, false, false, amqp.Table{ "x-message-ttl": int32(60000), "x-dead-letter-exchange": "webhooks.direct", "x-dead-letter-routing-key": "webhooks.process", }) if err != nil { return err } // Tier 3: Permanent Poison Queue for human/automated replay _, err = ch.QueueDeclare("webhooks.dlq.poison.q", true, false, false, false, nil) return err } ``` --- ## 2. Tracking Retry Attempts via x-death Headers in Go Whenever RabbitMQ dead-letters a message, it automatically appends metadata to the **x-death** array header inside the AMQP delivery properties. Our Go consumer inspects the retry count header and decides whether to route a failed delivery to the **10s queue**, the **60s queue**, or the **Poison DLQ**: ```go package consumer import ( "context" amqp "github.com/rabbitmq/amqp091-go" ) func HandleWebhookDelivery(ctx context.Context, ch *amqp.Channel, msg amqp.Delivery) error { attempt := getRetryAttempt(msg.Headers) err := processWebhookPayload(ctx, msg.Body) if err == nil { return msg.Ack(false) } nextRoutingKey := "webhooks.dlq.poison" if isTransientError(err) { switch attempt { case 0: nextRoutingKey = "webhooks.retry.10s" case 1: nextRoutingKey = "webhooks.retry.60s" default: nextRoutingKey = "webhooks.dlq.poison" } } headers := msg.Headers if headers == nil { headers = amqp.Table{} } headers["x-retry-attempt"] = int32(attempt + 1) pubErr := ch.PublishWithContext(ctx, "webhooks.dlx", nextRoutingKey, false, false, amqp.Publishing{ Headers: headers, ContentType: msg.ContentType, DeliveryMode: amqp.Persistent, Body: msg.Body, }) if pubErr != nil { // If broker publish fails, nack with requeue so message is never lost return msg.Nack(false, true) } return msg.Ack(false) } ``` --- ## 3. Idempotency Keys at the Database Boundary Because RabbitMQ provides **at-least-once delivery**, a webhook may occasionally be delivered twice if a worker crashes after committing the database state but before sending the AMQP **Ack**. Every incoming webhook event carries a unique provider event ID. Inside PostgreSQL, we insert the event ID into a **processed_webhook_events** table using **INSERT ... ON CONFLICT (event_id) DO NOTHING** inside the same SQL transaction as the business state update. Duplicate deliveries become safe no-ops in under **1.2ms**. --- ## Production Impact - **Message Loss Rate:** 0.00% across downstream database restarts and third-party API brownouts - **Head-of-Line Blocking:** Eliminated; live webhook P95 processing time stayed below **18ms** even while thousands of retry messages waited in the 10s and 60s delay queues - **Operational Recovery:** Malformed poison messages are isolated cleanly with full failure stack traces and can be replayed with a single CLI command once patched. --- ### 28. Why We Used Rust, Axum, and SQLx FOR UPDATE Locking to Hit 8,420 RPS at 3.82ms P95 Latency - **Canonical URL:** https://shafiktanbir.com/blog/rust-axum-sqlx-high-throughput-checkout-8420-rps - **Category:** Systems Engineering & Rust | **Published:** 2026-10-27 | **Read Time:** 4 min read - **Summary:** How we engineered a high-throughput e-commerce order engine in Rust using Axum 0.7, Tokio, and SQLx pessimistic row locking to sustain 8,420 requests per second at 3.82ms P95 latency with zero GC pauses. ## The Tail-Latency Problem Under Heavy Order Contention When thousands of buyers hit a checkout endpoint at the same time, average latency is a vanity metric. What actually breaks checkout conversion is **P95 and P99 tail latency**. In garbage-collected runtimes, sudden 10x bursts in concurrent order validation and inventory locking often trigger stop-the-world GC pauses right when database row locks are held. Even a 45ms GC pause inside an active transaction increases lock hold time, causing a queue buildup across every waiting connection in the pool. When we architected our high-throughput e-commerce order engine, our goal was not just a high peak request rate. Our goal was **flat, predictable P95 latency under heavy write contention**. We built the core checkout service in **Rust** using **Axum 0.7**, **Tokio**, and **SQLx** backed by **PostgreSQL 16**. Under verified load testing, the service sustained **8,420 requests per second (RPS)** at **3.82ms P95 latency** with zero inventory over-selling. --- ## 1. Compile-Time Verified SQL with SQLx and Pessimistic Row Locking ORM layers often hide expensive query patterns behind innocent-looking method calls. We used **SQLx** so every SQL query is type-checked directly against the live PostgreSQL schema at compile time. If a column type or nullability constraint changes in a migration, the Rust binary refuses to compile. To prevent race conditions when two concurrent orders attempt to reserve the same SKU, we used explicit **SELECT ... FOR UPDATE** row-level locking scoped to the exact inventory row inside a short-lived transaction: ```rust use sqlx::{Postgres, Transaction}; use uuid::Uuid; pub async fn reserve_inventory_sku( tx: &mut Transaction<'_, Postgres>, sku_id: Uuid, requested_qty: i32, ) -> Result { let row = sqlx::query!( r#" SELECT available_qty FROM inventory_items WHERE id = $1 FOR UPDATE "#, sku_id ) .fetch_optional(&mut **tx) .await? .ok_or(AppError::SkuNotFound)?; if row.available_qty < requested_qty { return Err(AppError::InsufficientInventory { available: row.available_qty, requested: requested_qty, }); } let updated = sqlx::query!( r#" UPDATE inventory_items SET available_qty = available_qty - $2, updated_at = NOW() WHERE id = $1 RETURNING available_qty "#, sku_id, requested_qty ) .fetch_one(&mut **tx) .await?; Ok(updated.available_qty) } ``` ### Why Deterministic Lock Ordering Matters If a cart contains multiple SKUs (for example, SKU B and SKU A), locking them in the order the client sent them can immediately cause a PostgreSQL deadlock when another user checks out with SKU A and SKU B in reverse order. Before opening the transaction, we sort all SKU UUIDs in ascending lexicographical order in memory. Every concurrent worker acquires row locks in the exact same sequence, reducing deadlock errors to **0.00%**. --- ## 2. Keeping Transactions Sub-Millisecond A pessimistic **FOR UPDATE** lock is only fast if the transaction holding it does zero network I/O outside the database. We enforced three strict rules on the checkout hot path: 1. **Zero external HTTP calls inside a database transaction:** Payment gateway intent creation and webhook signing happen outside the SQL transaction boundary using idempotency keys. 2. **Bounded connection pool sizing:** We tuned the SQLx Postgres pool to match physical CPU cores rather than setting an arbitrary high connection limit that causes PostgreSQL context-switching thrash. 3. **Zero heap allocations on validation paths:** Request payloads are validated using borrowed slices where possible before touching the database pool. ```rust use axum::{extract::State, Json}; use std::sync::Arc; pub async fn create_order_handler( State(state): State>, Json(mut payload): Json, ) -> Result, AppError> { payload.items.sort_by_key(|item| item.sku_id); let mut tx = state.db_pool.begin().await?; for item in &payload.items { reserve_inventory_sku(&mut tx, item.sku_id, item.quantity).await?; } let order_id = insert_order_record(&mut tx, &payload).await?; tx.commit().await?; Ok(Json(OrderResponse { order_id, status: "RESERVED", })) } ``` --- ## 3. Fast CI Builds with Cargo-Chef Multi-Stage Containers One common complaint about Rust in production is slow Docker build times in CI/CD pipelines. Recompiling the entire crate dependency tree on every commit wastes 12 to 18 minutes per deploy. We solved this using **cargo-chef** in a multi-stage Dockerfile so third-party crates are compiled and cached in a dedicated layer that only invalidates when **Cargo.toml** or **Cargo.lock** changes: ```dockerfile FROM lukemathwalker/cargo-chef:latest-rust-1.80 AS chef WORKDIR /app FROM chef AS planner COPY . . RUN cargo chef prepare --recipe-path recipe.json FROM chef AS builder COPY --from=planner /app/recipe.json recipe.json RUN cargo chef cook --release --recipe-path recipe.json COPY . . RUN cargo build --release --bin ecommerce-core FROM debian:bookworm-slim AS runtime WORKDIR /app COPY --from=builder /app/target/release/ecommerce-core /usr/local/bin/ecommerce-core ENTRYPOINT ["/usr/local/bin/ecommerce-core"] ``` --- ## Verified Production Benchmark Results Under sustained load testing against the containerized Axum + SQLx service and PostgreSQL 16: - **Sustained Throughput:** 8,420 requests per second (RPS) - **P95 Latency:** 3.82ms - **Inventory Over-Selling:** 0.00% across concurrent multi-item cart checkouts - **Runtime Memory Footprint:** Under 42 MB RSS under full load You do not need Rust for every internal admin CRUD service. When a single hot path governs revenue, inventory integrity, and tail latency under burst load, combining **Axum**, **SQLx compile-time checks**, and **sorted pessimistic locking** delivers predictable performance without over-provisioning cloud hardware. --- ### 29. Why 10,000 Users Clicking Buy at Once Broke Our Database (And How 28 Lines of Go + Redis Lua Fixed It) - **Canonical URL:** https://shafiktanbir.com/blog/6ade7149a592b1fcda27e7af - **Category:** Distributed Systems & High Concurrency | **Published:** 2026-10-25 | **Read Time:** 4 min read - **Summary:** How we eliminated race conditions and achieved 0.00% double-booking under 10,000 concurrent requests by moving seat reservation locks from PostgreSQL into atomic Redis EVALSHA Lua scripts with 60-second self-healing TTLs. ## Executive Summary & Production Diagnostic When flash-sale or ticket-reservation systems scale past **10,000 concurrent buyers** clicking **Buy** in the same 500-millisecond window, standard relational database transactions collapse. The failure is rarely caused by slow CPUs. It is caused by **row-level lock contention, serial queue buildup, and connection pool starvation**. In a standard textbook reservation flow, an application reads the available stock, checks if it is greater than zero, and issues an update statement: ```sql -- Standard Textbook Reservation Flow (Fails Under 10,000 RPS) SELECT available_stock FROM inventory WHERE item_id = 'item_42' FOR UPDATE; UPDATE inventory SET available_stock = available_stock - 1 WHERE item_id = 'item_42' AND available_stock > 0; ``` In local testing or at 20 requests per second, this works fine. Under a 10,000-user flash-sale spike, two failure modes occur immediately: - **Without row locking:** Hundreds of concurrent workers read positive stock at the exact same microsecond and oversell the inventory. - **With pessimistic row locking:** 9,999 database connections block in a serial queue waiting on a single PostgreSQL row lock, exhausting your PgBouncer pool and spiking P99 latency into multi-second timeouts. --- ## Technical Metric Benchmark Comparison | Metric / Benchmark Area | Initial Postgres Row-Lock State | Post-Redis Lua (EVALSHA) Engine | Improvement / Impact | | :--- | :--- | :--- | :--- | | **P95 Reservation Latency** | 3,850ms (Pool Timeout) | **3.9ms** | **99.8% Latency Drop** | | **Double-Booking / Oversell Rate** | 4.2% under race conditions | **0.00% (100/100 Exact)** | **Zero Race Conditions** | | **PostgreSQL Primary CPU Load** | 96% (Lock Wait Saturation) | **11% (Async Ledger Writes)** | **88.5% CPU Reduction** | | **Concurrent Buyers Verified** | Choked at ~600 parallel users | **10,000 Concurrent Goroutines** | **16x Throughput Scale** | --- ## Architecture Pivot: Atomic Gatekeeping at the Edge with Redis Lua Instead of forcing PostgreSQL to absorb 10,000 competing row locks on a hot inventory row, we moved the **reservation gatekeeper** into Redis using a pre-loaded Lua script executed via SHA digest. Why Lua inside Redis? Because Redis executes a Lua script **atomically on a single thread**. No other command can interleave between checking user idempotency, reading the stock counter, decrementing stock, and creating a 60-second payment hold TTL. ```lua -- KEYS[1]: stock_key (e.g., "drop:item:42:stock") -- KEYS[2]: hold_key (e.g., "drop:item:42:hold:user_991") -- ARGV[1]: requested_qty (1) -- ARGV[2]: ttl_seconds (60) -- 1. Idempotency guard: block duplicate clicks from the same buyer if redis.call("EXISTS", KEYS[2]) == 1 then return -2 -- Buyer already holds an active reservation end -- 2. Verify available inventory local current_stock = tonumber(redis.call("GET", KEYS[1]) or "0") local qty = tonumber(ARGV[1]) if current_stock < qty then return -1 -- Sold out end -- 3. Atomically decrement stock and create self-healing 60s hold redis.call("DECRBY", KEYS[1], qty) redis.call("SETEX", KEYS[2], tonumber(ARGV[2]), qty) return current_stock - qty ``` --- ## How Self-Healing 60-Second Holds Work Reserving the item at the edge is only half the architecture. What happens when a buyer reserves the last unit and closes their browser tab without completing checkout? ### 1. Fast Edge Reservation (Under 4ms) The Go API executes the pre-loaded Lua script in Redis. If it returns zero or higher, the buyer receives a signed 60-second checkout token and an asynchronous reservation event is published to our worker queue. ### 2. Asynchronous PostgreSQL Ledger Persistence When the payment webhook confirms checkout within the 60-second window, our background worker writes the finalized order into PostgreSQL and removes the temporary hold key. ### 3. Automatic Inventory Recovery on Abandonment If the 60-second TTL expires without payment confirmation, a lightweight reconciliation loop restores the expired hold quantity back to the Redis stock pool, requiring zero manual database cleanup. --- ## Proving Zero Race Conditions Under Load We never trust concurrency claims without deterministic race-detector verification. We wrote a Go concurrency harness spawning **10,000 parallel goroutines** competing simultaneously for **100 available items**: ```go func TestConcurrentFlashSaleReservations(t *testing.T) { const totalBuyers = 10000 const initialStock = 100 var successCount int64 var wg sync.WaitGroup wg.Add(totalBuyers) for i := 0; i < totalBuyers; i++ { go func(userID int) { defer wg.Done() reserved, err := engine.ReserveSeat(ctx, "item-42", fmt.Sprintf("user-%d", userID), 1) if err == nil && reserved { atomic.AddInt64(&successCount, 1) } }(i) } wg.Wait() if successCount != initialStock { t.Fatalf("expected exactly %d reservations, got %d", initialStock, successCount) } } ``` --- ## Key Takeaways for Founders & Engineering Leaders 1. **Protect PostgreSQL from hot-key lock storms:** Use PostgreSQL as your durable financial ledger of record, not as a 10,000-RPS spinlock counter. 2. **Never split check-and-decrement across network round-trips:** Always fuse stock verification and decrementing into a single atomic Redis Lua execution. 3. **Every inventory hold must have a deterministic TTL:** Unbounded holds turn abandoned carts into permanent inventory deadlocks during high-traffic launches. --- ### 30. Solving N+1 Database Query Bottlenecks and Connection Exhaustion in Node.js & Go Microservices - **Canonical URL:** https://shafiktanbir.com/blog/solving-n-plus-1-database-query-bottlenecks-nodejs-go - **Category:** Database & Performance | **Published:** 2026-10-02 | **Read Time:** 4 min read - **Summary:** An engineering breakdown on fixing N+1 database query loops, implementing DataLoader batching, and optimizing ORM query execution to drop P95 API response times from 1,850ms to 24ms under high traffic. ## Executive Summary & Performance Diagnostic In high-concurrency Node.js and Go microservices, one of the most common causes of silent API latency spikes is the **N+1 Database Query Pattern**. While Object-Relational Mappers (ORMs) like Prisma, TypeORM, or GORM simplify rapid product development, naive relational queries execute `N+1` separate SQL SELECT requests to fetch related child entities. During a recent backend performance optimization sprint for a multi-tenant B2B SaaS application, peak-hour dashboard load times reached a severe P95 latency wall of **1,850ms (1.85 seconds)**. PostgreSQL connection pools were saturating completely at **8,000 requests per minute (~133 RPS peak)**, triggering socket timeouts and pool acquisition deadlocks. This case study demonstrates how we identified N+1 query patterns using `pg_stat_statements` and SQL query logging, re-architected ORM data fetching with batching (DataLoader pattern) and JOIN projection, and dropped P95 API latency to **24.1ms (a 98.7% reduction)** while cutting database CPU load from **88% to 12%**. --- ## Technical Metric Benchmark Comparison | Metric / Benchmark Area | Initial Production State | Post-Optimization Benchmark | Improvement / Impact | | :--- | :--- | :--- | :---: | | **P95 API Latency** | 1,850ms (1.85 sec) | **24.1ms** | **98.7% Latency Drop** | | **SQL Queries Per Request** | 127 queries / API call | **2 queries / API call** | **98.4% Query Volume Drop** | | **PostgreSQL Pool Saturation** | 100% (Connection Exhaustion) | **18% (Healthy Reserve)** | **Zero Connection Timeouts** | | **Primary Database CPU** | 88% Load | **12% Load** | **76% CPU Reduction** | --- ## Root Cause Analysis: The Silent N+1 Loop Using distributed tracing and SQL log analyzers, we discovered that requesting a list of 50 accounts on the dashboard executed **1 initial query for accounts** plus **50 separate queries for users** and **76 queries for subscription permissions**: ```sql -- 1. Initial SELECT query for Accounts: SELECT id, name, created_at FROM accounts LIMIT 50; -- 2. N Queries (Executed inside a loop for EACH account): SELECT id, account_id, email, role FROM users WHERE account_id = 'acc_101'; SELECT id, account_id, email, role FROM users WHERE account_id = 'acc_102'; -- ... (Repeated 48 more times) -- 3. Additional Child N Queries (Executed for each user's permissions): SELECT * FROM permissions WHERE user_id = 'usr_501'; -- ... (Repeated 75 more times) ``` At **8,000 requests/minute (~133 RPS)**, this single endpoint (`127` SQL queries per call) forced PostgreSQL to execute **1,016,000 individual SELECT queries per minute**, thrashing the connection pool and locking database worker threads. --- ## Step-by-Step Remediation Engineering ### 1. Batching with IN Clause & DataLoader Pattern Instead of looping over each parent record to fetch child entities, we implemented **in-memory request batching** (DataLoader pattern in Node.js / Go channel batching): ```typescript // Before (N+1 Query Loop): const accounts = await prisma.account.findMany({ take: 50 }); for (const acc of accounts) { acc.users = await prisma.user.findMany({ where: { accountId: acc.id } }); // N+1 loop } // After (Batched Relational Fetch): const accounts = await prisma.account.findMany({ take: 50 }); const accountIds = accounts.map(a => a.id); // Executed as 1 single query using SQL IN operator: const users = await prisma.user.findMany({ where: { accountId: { in: accountIds } } }); // Map users back to accounts in memory (O(1) Hash Map lookup): const userMap = new Map(); for (const u of users) { const list = userMap.get(u.accountId) || []; list.push(u); userMap.set(u.accountId, list); } for (const acc of accounts) { acc.users = userMap.get(acc.id) || []; } ``` ### 2. SQL JOIN & Select Field Projection To further reduce memory allocation and database I/O, we replaced ORM auto-selects (`SELECT *`) with explicit SQL projection: ```sql -- Bound parent accounts to 50 rows first so child user joins never truncate parent pagination: WITH page_accounts AS ( SELECT id, name, created_at FROM accounts WHERE status = 'ACTIVE' ORDER BY created_at DESC LIMIT 50 ) SELECT pa.id AS account_id, pa.name AS account_name, u.id AS user_id, u.email AS user_email, u.role AS user_role FROM page_accounts pa LEFT JOIN users u ON pa.id = u.account_id ORDER BY pa.created_at DESC; ``` --- ## Final Production Impact 1. **API Response Latency:** Dropped P95 dashboard loading time from **1,850ms to 24.1ms**. 2. **Database Throughput:** Reduced total SQL executions from 1,016,000 queries/min to under 16,000 queries/min. 3. **Infrastructure Stability:** Eliminated database connection pool exhaustion errors completely during high-traffic marketing campaigns. --- ### 31. How We Reduced P95 PostgreSQL Query Latency from 4.2s to 14ms Under 15,000 RPS - **Canonical URL:** https://shafiktanbir.com/blog/postgresql-latency-optimization-p95 - **Category:** Database & Performance | **Published:** 2026-10-02 | **Read Time:** 4 min read - **Summary:** An architectural deep-dive on fixing unindexed composite query execution plans, PgBouncer pool sizing, and partial B-Tree index optimization under extreme SaaS load. ## Executive Summary & Production Diagnostic When multi-tenant B2B SaaS platforms scale toward **15,000 Requests Per Second (RPS) platform-wide**, database performance degradation is rarely caused by "slow hardware." It is almost exclusively caused by **unindexed composite filtering, buffer cache thrashing, and connection starvation**. During a recent backend performance optimization sprint for a high-throughput SaaS platform, peak-hour API requests were hitting a severe P95 latency wall of **4,200ms (4.2 seconds)**. The primary Multi-AZ RDS PostgreSQL instance was pegged at **92% CPU utilization**, triggering read timeouts and database pool exhaustion. This case study breaks down how we used `pg_stat_statements`, `EXPLAIN (ANALYZE, BUFFERS)`, partial B-Tree indexing, and PgBouncer transaction-level connection pooling to drop P95 API response times to **14.2ms (a 99.6% reduction)** while cutting RDS Multi-AZ + read-replica costs by **$2,400/month**. --- ## Technical Metric Benchmark Comparison | Metric / Benchmark Area | Initial Production State | Post-Optimization Benchmark | Improvement / Impact | | :--- | :--- | :--- | :---: | | **P95 API Response Latency** | 4,200ms (4.2 sec) | **14.2ms** | **99.6% Latency Drop** | | **PostgreSQL Primary CPU Load** | 92% (Sustained Bottleneck) | **14% (Idle Headroom)** | **84.7% CPU Reduction** | | **Shared Buffer Hit Ratio** | 82.4% (Disk I/O Thrashing) | **99.8% (In-Memory)** | **Near-Zero Disk I/O** | | **RDS Cluster Monthly Cost** | $3,600 / mo (Multi-AZ db.r6g.4xlarge primary + replica) | **$1,200 / mo (Multi-AZ db.r6g.xlarge)** | **$2,400/mo ($28.8k/yr) Saved** | --- ## Root Cause Analysis: The 22M Row Sequential Scan Using `pg_stat_statements` ordered by `total_exec_time`, we isolated a single telemetry query executing over 4,000 times per minute inside the wider 15,000 RPS cluster workload: ```sql -- Slow Query Pattern: SELECT id, tenant_id, payload, created_at FROM tenant_events WHERE tenant_id = 'tenant_9941' AND status = 'PROCESSED' ORDER BY created_at DESC LIMIT 50; ``` Running `EXPLAIN (ANALYZE, BUFFERS)` revealed that PostgreSQL was forced to scan **22,400,000 rows** sequentially because existing indexes only covered `tenant_id` independently. ``` -- EXPLAIN Output: Seq Scan on tenant_events (cost=0.00..682490.12 rows=52 width=142) (actual time=4182.110..4189.421 rows=50 loops=1) Filter: ((status = 'PROCESSED'::text) AND (tenant_id = 'tenant_9941'::text)) Buffers: shared read=84102 hit=1204 ``` --- ## Step-by-Step Remediation Engineering ### 1. Partial Composite B-Tree Indexing Instead of creating a massive index on all 22 million rows (which inflates WAL write latency), we engineered a **Partial Composite B-Tree Index** targeting only active/processed records: ```sql -- 1. Create Partial Composite Index without blocking production writes CREATE INDEX CONCURRENTLY idx_events_tenant_created_partial ON tenant_events (tenant_id, created_at DESC) WHERE status = 'PROCESSED'; ``` **Why this worked:** - **Index Size Reduction:** The index size dropped from 1.4 GB down to **180 MB**, allowing the entire index to permanently reside in PostgreSQL `shared_buffers` RAM. - **Zero Write Amplification:** Inserts for un-processed rows bypass the index entirely. ### 2. Verified Execution Plan (`EXPLAIN ANALYZE`) After applying the partial index, the query execution plan shifted from a 4.2-second Sequential Scan to a lightning-fast Index Scan: ``` -- Post-Index EXPLAIN Output: Index Scan using idx_events_tenant_created_partial on tenant_events (actual time=0.042..0.088 rows=50 loops=1) Index Cond: (tenant_id = 'tenant_9941'::text) Buffers: shared hit=4 read=0 -- Execution Time: 0.120 ms! ``` ### 3. PgBouncer Transaction Pool Tuning To prevent microservice container restarts from exhausting PostgreSQL backends: - Deployed **PgBouncer** in front of RDS. - Switched pool mode to `transaction`. - Set `default_pool_size = 30` with `max_client_conn = 5000`. --- ## Key Lessons for Engineering Leaders 1. **Beware of Single-Column Indexes:** Multiple single-column indexes on high-cardinality tables force PostgreSQL to perform Bitmap Index Scans, which degrade heavily under concurrency. 2. **Use Partial Indexes:** If 80% of your queries filter on `status = 'active'`, make your index partial. You will save gigabytes of RAM and speed up write operations. 3. **Monitor `shared_buffers` Hit Ratio:** If your buffer hit ratio drops below 99%, your database is reading from EBS block storage instead of RAM. --- ### 32. Scaling Production RAG Pipelines: Vector DB Optimization & Fallback LLM Routing - **Canonical URL:** https://shafiktanbir.com/blog/6abec13987bd6aa792690cb4 - **Category:** AI Infrastructure | **Published:** 2026-01-18 | **Read Time:** 1 min read - **Summary:** How to build production-grade RAG infrastructure using FastAPI, Pinecone vector indexing, hybrid semantic search, and fallback LLM model orchestration. ## Production RAG Architecture Taking Retrieval-Augmented Generation (RAG) applications from local demo notebooks into high-throughput production requires solving latency bottlenecks, hallucination risks, and LLM API rate limits. ### 3 Key Architectural Pillars 1. **Semantic Chunking & Embedding:** Replacing fixed character splitters with document-structure aware chunking (512 tokens with 50-token overlap). 2. **Hybrid Vector & BM25 Search:** Combining Pinecone dense vector embeddings with sparse BM25 keyword matching for high-precision retrieval. 3. **Cross-Encoder Re-Ranking:** Reranking top-20 retrieved candidates down to the 5 most relevant context passages before prompt injection. ### Fallback LLM Model Orchestration By integrating FastAPI orchestrators with Model Context Protocol (MCP) tool execution and automated fallback routing (OpenAI → Anthropic → Local VLLM), service uptime is guaranteed even during primary LLM provider outages. --- ### 33. Cutting AWS Compute Bills by 35% with K3s Pod Request Tuning - **Canonical URL:** https://shafiktanbir.com/blog/cutting-aws-compute-bills-k3s - **Category:** Cloud Infrastructure | **Published:** 2025-11-14 | **Read Time:** 4 min read - **Summary:** A deep dive into pod CPU and memory request right-sizing, Horizontal Pod Autoscaling (HPA), and eliminating idle worker node compute waste. ## Executive Summary & Background When high-growth B2B SaaS platforms scale past $1M ARR, monthly AWS cloud compute bills frequently double faster than subscription revenue. During an infrastructure diagnostic audit for a multi-tenant SaaS platform, the monthly AWS compute bill had reached **$6,200/month**. The cluster was running **8 m6i.4xlarge EC2 worker nodes** (16 vCPU, 64GB RAM each, plus attached EBS volumes and NAT traffic), yet overall node CPU utilization averaged less than **6.5%**. This case study demonstrates how we conducted an empirical 30-day Prometheus metrics audit, right-sized pod resource requests to match actual P95 consumption, and deployed Horizontal Pod Autoscaling (HPA) alongside Cluster Autoscaler — reducing the active worker node footprint from **8 instances to 5 instances**, saving **$2,170/month ($26,040/year, 35% compute reduction)** with zero downtime. --- ## Financial Impact & Metrics Comparison | Optimization Metric | Pre-Audit Cluster State | Post-Optimization State | Financial Impact / Benefit | | --- | --- | --- | --- | | **EC2 Worker Node Count** | 8 x m6i.4xlarge Instances | 5 x m6i.4xlarge Instances | **37.5% Node Count Reduction** | | **Monthly AWS Compute Bill** | $6,200 / month | $4,030 / month | **$2,170/mo ($26,040/yr) Saved (-35%)** | | **Average Node CPU Utilization** | 6.2% (Massive Waste) | 58.4% (Optimal Efficiency) | **9x Resource Utilization Increase** | | **Pod OOMKilled Incidents** | 12 per month | 0 per month | **100% Application Stability** | --- ## Root Cause Analysis: The Idle Resource Trap In Kubernetes, worker node capacity is allocated based on **Resource Requests**, NOT actual CPU/RAM usage. Developers had configured default pod requests of `cpu: "2000m"` (2 vCPU cores) and `memory: "4Gi"` for every microservice container to prevent Out-Of-Memory (OOM) crashes during initial staging tests. When scaled across 20+ microservice replicas, Kubernetes reserved 32 vCPU cores on node capacity. The Kubernetes scheduler refused to schedule new pods on existing worker nodes, forcing AWS Autoscaling Groups to spin up 8 expensive EC2 instances even though actual CPU usage across the entire cluster was under 6%. ``` [ EC2 Worker Node (m6i.4xlarge): 16 vCPU / 64GB RAM ] ├── Pod A: Requested 4 CPU (Actual Avg: 0.1 CPU) ──▶ Reserved ├── Pod B: Requested 4 CPU (Actual Avg: 0.15 CPU) ──▶ Reserved ├── Pod C: Requested 4 CPU (Actual Avg: 0.08 CPU) ──▶ Reserved └── Scheduler Exhausted -> Forces extra EC2 node despite ~94% idle CPU ``` --- ## 3-Step Remediation Engineering ### Step 1: Scraping 30-Day P95/P99 Metrics with PromQL We deployed Prometheus and scraped container-level metrics across peak business hours to identify actual resource usage patterns: ```promql # 1. Scrape P95 CPU rate per microservice container over 30 days quantile_over_time(0.95, rate(container_cpu_usage_seconds_total{container!=""}[5m])[30d:5m]) # 2. Scrape P99 Memory working set bytes per container quantile_over_time(0.99, container_memory_working_set_bytes{container!=""}[30d]) # 3. Detect pods with excessive CPU request-to-usage ratio (> 10x gap) (sum(kube_pod_container_resource_requests{resource="cpu"}) by (pod) / sum(rate(container_cpu_usage_seconds_total[5m])) by (pod)) > 10 ``` --- ### Step 2: Right-Sizing Pod Requests & Limits Based on empirical PromQL data, we updated deployment manifests. We aligned **Requests** to actual P95 consumption and set **Limits** to P99 plus a 25% safety margin: ```yaml # k8s/deployments/backend-service.yaml apiVersion: apps/v1 kind: Deployment metadata: name: saas-api-backend namespace: production spec: replicas: 4 template: spec: containers: - name: api-server image: registry.company.com/api-server:v2.4.1 resources: requests: cpu: "150m" # Reduced from 2000m (P95 actual: 110m) memory: "256Mi" # Reduced from 4096Mi (P95 actual: 180Mi) limits: cpu: "500m" # Allows bursts during request spikes memory: "512Mi" # Prevents runaway memory leaks ``` --- ### Step 3: Configuring Horizontal Pod Autoscaling (HPA) Instead of running fixed replica counts, we configured HPA to scale dynamically based on custom HTTP request throughput metrics scraped from Traefik Ingress: ```yaml # k8s/autoscaling/hpa-backend.yaml apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: saas-api-backend-hpa namespace: production spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: saas-api-backend minReplicas: 3 maxReplicas: 16 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 - type: External external: metric: name: traefik_entrypoint_requests_per_second target: type: AverageValue averageValue: "150" behavior: scaleUp: stabilizationWindowSeconds: 0 policies: - type: Percent value: 100 periodSeconds: 15 scaleDown: stabilizationWindowSeconds: 300 policies: - type: Percent value: 25 periodSeconds: 60 ``` --- ## Final Results & Recommendations 1. **Immediate Compute Savings:** Safely drained and decommissioned 3 redundant worker nodes (8 -> 5 m6i.4xlarge), saving **$2,170/month ($26,040/year, 35% reduction)**. 2. **Zero Performance Loss:** Passed synthetic 5x traffic load tests with zero HTTP 5xx errors and sub-200ms P95 API latencies. 3. **Automated Scalability:** During marketing email blasts, HPA automatically scales backend pods from 3 to 12 replicas in under 20 seconds, scaling back down smoothly after traffic subsides. --- ### 34. Preventing Cascading Microservice Outages with Circuit Breakers & DLQs - **Canonical URL:** https://shafiktanbir.com/blog/6abec13987bd6aa792690cb5 - **Category:** Distributed Systems | **Published:** 2025-09-30 | **Read Time:** 1 min read - **Summary:** Implementing resilience patterns with Redis, RabbitMQ task queues, and Traefik ingress rate limiting to survive microservice downstream failures. ## System Architecture & Resilience Strategy When a single downstream service experiences latency or crashes under load, unhandled synchronous HTTP retries can trigger a cascading failure that brings down the entire application platform. ### 3 Key Resilience Patterns - **Circuit Breaker State Machine:** Transitioning endpoints between Closed, Open, and Half-Open states based on failure rate thresholds (e.g., 50% error rate over 10s). - **Asynchronous Task Offloading:** Moving heavy write operations to RabbitMQ queues backed by Celery background workers. - **Dead Letter Queues (DLQ):** Capturing poison-pill messages after 3 failed retries for isolated inspection without blocking queue processing. --- ### 35. Automating Zero-Downtime Deployments with ArgoCD & Custom Helm Charts - **Canonical URL:** https://shafiktanbir.com/blog/automating-zero-downtime-deployments-argocd-helm - **Category:** DevOps & GitOps | **Published:** 2025-08-20 | **Read Time:** 5 min read - **Summary:** A comprehensive B2B engineering case study on eliminating deployment drift, automated rolling updates, and instant rollbacks using GitOps pipelines. ## Executive Summary & Background In high-velocity tech teams, relying on manual deployment scripts or imperative `kubectl apply` commands executed from developer laptops is a primary cause of production outages. Prior to this GitOps transformation, a growing B2B SaaS platform experienced recurring downtime during weekly production releases. Configuration drift between staging and production environments frequently caused hidden environment variable mismatches, while manual rollback procedures took upwards of 35 minutes to diagnose and resolve. This case study breaks down how we engineered an automated, declarative GitOps continuous delivery pipeline using **ArgoCD**, **custom Helm v3 charts**, and **GitHub Actions CI security gates** — achieving **0ms deployment downtime** and **instant automated rollbacks**. --- ## The Core Challenges & Production Metrics | Metric / Metric Area | Before GitOps Implementation | After ArgoCD & Helm Automation | | --- | --- | --- | | **Release Downtime** | 4 – 15 minutes per release | **0ms (Zero Downtime)** | | **Deployment Drift** | High (100% manual drift risk) | **0% (Automated Reconciliation)** | | **Rollback Resolution Time** | 35+ minutes (Manual debug) | **< 30 seconds (Automated)** | | **Security Scanning Gate** | None (Post-deploy discovery) | **Automated Trivy CI Vulnerability Gate** | --- ## Target GitOps Architecture The architecture separates concerns into two distinct pipelines: 1. **Continuous Integration (CI):** Runs in GitHub Actions. Builds Docker container images, executes unit/integration tests, runs Trivy vulnerability scans, and updates the Helm values repository. 2. **Continuous Delivery (CD):** Managed by ArgoCD inside the Kubernetes control plane. Continuously monitors the target Git manifest repository and reconciles any cluster drift within 30 seconds. ``` [ Developer Commit ] │ ▼ [ GitHub Actions CI ] ──▶ (Trivy Security Scan + Build Container Image) │ ▼ [ Update Helm Git Repo ] │ ▼ [ ArgoCD Control Plane ] ──▶ (Detects Drift & Syncs Declaratively) │ ▼ [ K3s / EKS Cluster ] ──▶ (Zero-Downtime Rolling Update: maxSurge 25%) ``` --- ## Engineering Implementation Step-by-Step ### 1. Custom Helm Chart Rolling Update Strategy To guarantee zero-downtime releases, we structured custom Helm charts with strict readiness probes, liveness probes, and rolling update strategy definitions: ```yaml # templates/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: {{ include "saas-backend.fullname" . }} labels: app.kubernetes.io/name: {{ include "saas-backend.name" . }} spec: replicas: {{ .Values.replicaCount }} strategy: type: RollingUpdate rollingUpdate: maxSurge: 25% # Spin up new pods before killing old ones maxUnavailable: 0% # Never drop capacity below 100% selector: matchLabels: app.kubernetes.io/name: {{ include "saas-backend.name" . }} template: metadata: labels: app.kubernetes.io/name: {{ include "saas-backend.name" . }} spec: containers: - name: {{ .Chart.Name }} image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}" imagePullPolicy: {{ .Values.image.pullPolicy }} ports: - name: http containerPort: 8080 readinessProbe: httpGet: path: /healthz/ready port: http initialDelaySeconds: 5 periodSeconds: 5 failureThreshold: 3 livenessProbe: httpGet: path: /healthz/live port: http initialDelaySeconds: 15 periodSeconds: 10 resources: requests: cpu: 250m memory: 512Mi limits: cpu: 1000m memory: 1024Mi ``` --- ### 2. ArgoCD Declarative Application Specification We deployed ArgoCD to manage application lifecycle states declaratively. The Application manifest below enforces automated prune and self-healing mechanisms: ```yaml # argocd/application-production.yaml apiVersion: argoproj.io/v1alpha1 kind: Application metadata: name: production-backend-service namespace: argocd finalizers: - resources-finalizer.argocd.argoproj.io spec: project: default source: repoURL: 'https://github.com/org/k8s-manifests.git' targetRevision: HEAD path: 'charts/saas-backend' helm: valueFiles: - values-production.yaml destination: server: 'https://kubernetes.default.svc' namespace: production syncPolicy: automated: prune: true # Delete resources removed from Git selfHeal: true # Overwrite manual cluster modifications syncOptions: - CreateNamespace=true - Validate=true - PruneLast=true retry: limit: 5 backoff: duration: 5s factor: 2 maxDuration: 3m ``` --- ### 3. Automated Security & Vulnerability Gating (DevSecOps) Before any Git commit triggers an ArgoCD sync, container images are scanned in GitHub Actions using **Trivy**. If a HIGH or CRITICAL vulnerability is detected in base dependencies, the build fails and blocks the release: ```yaml # .github/workflows/ci-pipeline.yml name: Continuous Integration & Vulnerability Scan on: push: branches: [ main ] jobs: security-and-build: runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v4 - name: Build Local Container Image run: | docker build -t saas-backend:latest . - name: Run Trivy Vulnerability Scanner uses: aquasecurity/trivy-action@master with: image-ref: 'saas-backend:latest' format: 'table' exit-code: '1' ignore-unfixed: true vuln-type: 'os,library' severity: 'CRITICAL,HIGH' - name: Push Container Image to Registry if: success() run: | docker tag saas-backend:latest registry.company.com/saas-backend:latest docker push registry.company.com/saas-backend:latest ``` --- ## Results & Financial Impact 1. **100% Zero-Downtime Releases:** Rolling deployment strategy with `maxUnavailable: 0%` ensures that new pods pass health checks before old pods are terminated. 2. **Zero Deployment Drift:** ArgoCD self-healing automatically reverts unauthorized `kubectl` mutations within 30 seconds. 3. **Automated Incident Defense:** If a bad image fails readiness probes during rollout, ArgoCD halts deployment progression, keeping 100% of production user traffic served by healthy previous pods. --- ## Key Recommendations for Engineering Leaders - **Never deploy without readiness probes:** Without a valid readiness probe, Kubernetes will route public HTTP traffic to pods before their internal application framework has initialized. - **Decouple CI from CD:** Keep Docker container image building (CI) in your forge (GitHub Actions / GitLab CI), but leave cluster state reconciliation (CD) strictly to pull-based operators like ArgoCD inside the control plane. --- ### 36. Reducing P95 API Latency from 2.5s to 180ms with Redis & PostgreSQL Tuning - **Canonical URL:** https://shafiktanbir.com/blog/reducing-p95-api-latency-redis-postgres - **Category:** Backend Performance | **Published:** 2024-12-10 | **Read Time:** 4 min read - **Summary:** Fixing database query bottlenecks, N+1 query patterns, and implementing Redis distributed caching layers for high-throughput endpoints. ## Executive Summary & Background API response times exceeding 2,000ms directly cause user churn, abandoned checkout carts, and customer dissatisfaction. During an emergency backend performance audit for a high-traffic SaaS client, P95 API response times were reaching **2,500ms** during peak business hours. Database CPU utilization on the primary PostgreSQL instance spiked above **88%**, resulting in database connection timeouts and failed HTTP requests. This case study breaks down how we diagnosed full table scans on a **15-million row table**, fixed N+1 ORM query loops, implemented composite B-Tree indexing, deployed a Redis Cache-Aside layer, and configured PgBouncer connection pooling — dropping P95 API latency by **92.8% to 180ms**. --- ## Performance Benchmark Comparison | Benchmark Metric | Initial Unoptimized Backend | Post-Optimization Backend | Performance Improvement | | --- | --- | --- | --- | | **P95 API Latency** | 2,500ms (2.5 seconds) | **180ms** | **92.8% Latency Drop** | | **Primary DB CPU Usage** | 88% (Near Collapse) | **18% (Idle Capacity)** | **70% CPU Load Reduction** | | **Max Throughput (RPS)** | 120 Requests / sec | **1,450 Requests / sec** | **12x Capacity Increase** | | **Database Connection Failures** | 45 errors / hour | **0 errors / hour** | **100% Uptime & Stability** | --- ## Root Cause Diagnostics Using APM distributed tracing (OpenTelemetry) and PostgreSQL slow query logging (`pg_stat_statements`), we identified three severe bottlenecks: 1. **Missing Composite Index on 15M Rows:** The main dashboard query performed a full sequential scan across 15,000,000 records to filter by `tenant_id` and `status` while sorting by `created_at`. Each query took **1,250ms**. 2. **N+1 ORM Query Loop:** The user list endpoint fetched 50 items in Query 1, then executed 50 individual SQL queries inside a loop to fetch nested user permissions. 3. **Database Connection Overhead:** Backend microservices spawned new TCP database connections on every incoming HTTP request, consuming 35% of PostgreSQL server RAM on idle process overhead. --- ## Step-by-Step Engineering Remediation ### Step 1: Composite B-Tree Indexing We analyzed `EXPLAIN ANALYZE` execution plans and created targeted composite B-Tree indexes using non-blocking concurrent index creation: ```sql -- 1. Identify slow queries in pg_stat_statements SELECT query, calls, total_exec_time / calls AS avg_time_ms, rows FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5; -- 2. Create non-blocking composite index on tenant_id + status + created_at CREATE INDEX CONCURRENTLY idx_orders_tenant_status_created ON orders (tenant_id, status, created_at DESC); -- 3. Verify index usage with EXPLAIN (ANALYZE, BUFFERS) EXPLAIN (ANALYZE, BUFFERS) SELECT id, total_amount, created_at FROM orders WHERE tenant_id = 'tenant_9821' AND status = 'COMPLETED' ORDER BY created_at DESC LIMIT 50; ``` ```text Limit (cost=0.56..68.42 rows=50 width=24) (actual time=0.041..3.129 rows=50 loops=1) Buffers: shared hit=54 -> Index Scan using idx_orders_tenant_status_created on orders (actual time=0.039..3.112 rows=50 loops=1) Index Cond: ((tenant_id = 'tenant_9821'::text) AND (status = 'COMPLETED'::text)) Buffers: shared hit=54 Planning Time: 0.142 ms Execution Time: 3.184 ms ``` ### Step 2: PgBouncer Transaction Pooling ```ini [pgbouncer] pool_mode = transaction default_pool_size = 25 reserve_pool_size = 5 max_client_conn = 1000 server_idle_timeout = 60 ``` Switching backend workers to PgBouncer transaction pooling cut active PostgreSQL backend processes from 400+ down to a fixed 25-connection server pool, reclaiming ~35% RAM previously lost to connection allocation. ### Step 3: Redis Cache-Aside with Explicit Write Invalidation ```typescript const cacheKey = `orders:${tenantId}:completed:p1`; const cached = await redis.get(cacheKey); if (cached) return JSON.parse(cached); const rows = await db.query(HOT_ORDERS_SQL, [tenantId]); // 60s +/- 10s jitter prevents synchronized expiration spikes (cache stampede) const ttlSeconds = 60 + Math.floor(Math.random() * 10); await redis.set(cacheKey, JSON.stringify(rows), 'EX', ttlSeconds); // On order state transition in write path: await redis.del(cacheKey); ``` --- ## Final Technical Outcomes - **P95 Latency:** Reduced from **2,500ms to 180ms (92.8% decrease)**. - **Database CPU Load:** Dropped from **88% to 18%**, providing ample headroom for business growth. - **Cost Savings:** Avoided a $4,000/mo database hardware upgrade by optimizing existing open-source software layer configuration. --- ### 37. Scaling PostgreSQL for High Throughput: PgBouncer Pooling & Read Replicas - **Canonical URL:** https://shafiktanbir.com/blog/6abec13987bd6aa792690cb6 - **Category:** Database Engineering | **Published:** 2024-09-12 | **Read Time:** 1 min read - **Summary:** Architecting zero-downtime database replication, connection pool management, and automated read/write query routing. ## High-Throughput Database Architecture Direct application connections to PostgreSQL can quickly exhaust backend server process memory as user traffic scales. Transaction-level connection pooling and read-replica splitting unlock massive throughput gains. ### Architectural Highlights - **PgBouncer Transaction Pooling:** Reusing backend PostgreSQL process connections across thousands of incoming application client requests. - **Asynchronous Streaming Replication:** Offloading heavy analytics and read-only API queries to read-replicas. - **Automated Query Routing:** Configuring ORM routing layers to direct mutation queries to the primary database while routing analytics reads to replica nodes. --- ### 38. Hardening Kubernetes Clusters: RBAC, NetworkPolicies & Trivy Scanning - **Canonical URL:** https://shafiktanbir.com/blog/6abec13987bd6aa792690cb7 - **Category:** Cloud Security | **Published:** 2024-06-15 | **Read Time:** 1 min read - **Summary:** Locking down container workloads, enforcing namespace isolation, and passing enterprise B2B vendor security reviews. ## 3 Layers of Cluster Hardening Default Kubernetes setups allow unrestricted pod-to-pod network traffic and grant excessive ServiceAccount permissions. Passing enterprise B2B security questionnaires requires locking down cluster access boundaries. - **Granular RBAC:** Replacing cluster-admin bindings with scoped Roles and RoleBindings following the Principle of Least Privilege. - **NetworkPolicies Namespace Isolation:** Enforcing default-deny ingress and egress rules, explicitly whitelisting authorized inter-service communications. - **Container Image Scanning:** Integrating Trivy vulnerability scanning into CI/CD pipelines to block high/critical CVEs before container registry push. --- ### 39. Building a Zero-Trust Hybrid Cloud Mesh Network with Headscale WireGuard & Caddy - **Canonical URL:** https://shafiktanbir.com/blog/6abec13987bd6aa792690cb8 - **Category:** Cloud Networking | **Published:** 2023-12-04 | **Read Time:** 1 min read - **Summary:** Securing inter-node communication across multi-cloud VPS environments using self-hosted Headscale WireGuard VPN and automated TLS reverse proxies. ## Zero-Trust Architecture Connecting distributed VPS nodes across AWS, DigitalOcean, and private clouds without exposing database ports to the public internet requires a secure private mesh overlay network. - **Headscale WireGuard Mesh:** Deploying a self-hosted control plane for Tailscale WireGuard VPN, enabling encrypted point-to-point IPsec tunnel connections. - **Caddy Reverse Proxy:** Automating ACME TLS/SSL certificate lifecycle management and proxying internal microservices without public port exposure. - **Firewall Rules:** Locking down cloud security groups to restrict all inbound traffic except WireGuard UDP ports and HTTPS port 443. --- ### 40. Guaranteeing Database Persistence on Kubernetes with StatefulSets & PVCs - **Canonical URL:** https://shafiktanbir.com/blog/6abec13987bd6aa792690cb9 - **Category:** Kubernetes Architecture | **Published:** 2023-10-05 | **Read Time:** 1 min read - **Summary:** Architecting resilient storage classes for PostgreSQL and Redis state survival across worker node failures and pod evictions. ## The Architecture Pattern Running stateful databases inside Kubernetes requires careful volume binding to prevent data corruption during pod rescheduling. Deploying databases as simple Deployments leads to volume lock conflicts and data loss during node evictions. - **StatefulSets with VolumeClaimTemplates:** Ensures each database replica receives a unique, stable network identity and dedicated PersistentVolumeClaim (PVC). - **StorageClass Dynamic Provisioning:** Binding local high-performance NVMe storage or cloud block storage with automated snapshots. - **Disaster Recovery Simulation:** Testing control-plane failures and node terminations to verify state survival and automated master-replica failover within 60 seconds. --- ### 41. Building an Actionable Observability Pipeline with Prometheus, Grafana & Loki - **Canonical URL:** https://shafiktanbir.com/blog/6abec13987bd6aa792690cba - **Category:** Observability | **Published:** 2023-04-18 | **Read Time:** 1 min read - **Summary:** Transitioning from noisy alerts to actionable incident metrics and centralized structured logging across microservices. ## The 3 Pillars of Observability Without centralized observability, debugging production incidents requires SSHing into worker nodes and tailing log files — costing hours of downtime. - **Prometheus Metrics Scraping:** Scraping cluster infrastructure, node exporter, and custom application metrics. - **Loki Structured Logging:** Centralized log aggregation indexed by Kubernetes labels without expensive full-text indexing overhead. - **Grafana Alertmanager:** Routing critical P0 alerts (pod crash loops, disk space >90%) directly to Slack and PagerDuty while suppressing non-actionable noise. --- ### 42. Shifting Security Left: Automated Trivy Image Scanning in GitHub Actions - **Canonical URL:** https://shafiktanbir.com/blog/6abec13987bd6aa792690cbb - **Category:** DevSecOps | **Published:** 2023-01-22 | **Read Time:** 1 min read - **Summary:** Automating vulnerability scanning, rootless Docker builds, and SBOM generation in modern CI/CD delivery pipelines. ## DevSecOps Pipeline Strategy Fixing security vulnerabilities after a production deployment costs 10x more than catching them during continuous integration. Shifting security left integrates automated vulnerability gates into your git pull request workflow. - **Multi-Stage Distroless Docker Builds:** Using distroless base images to strip out shell utilities, reducing container attack surface by 80%. - **Trivy Vulnerability Gating:** Configuring GitHub Actions workflows to fail builds if unpatched HIGH or CRITICAL CVEs are detected. - **Software Bill of Materials (SBOM):** Generating CycloneDX SBOMs for enterprise audit compliance. ---