Overview
2026Distributed Systems & MicroservicesSTAR Case Study

StreamMart

I refactored an event-driven e-commerce backend with SKIP LOCKED outbox relays and idempotent eachBatch consumers, boosting throughput 7.76× to 375.75 checkouts/s at zero lag.

Diagram · Architecture Only

Diagram: Refactored SKIP LOCKED outbox relays, 20/20 Kafka outage recovery, eachBatch consumers, and .DLQ isolation.

375.75/s
Completed checkouts (100 VUs)
0 msgs
Full-pipeline lag @ 30s
500 / 500
Kafka outage zero-loss recovery
Backend Systems EngineerAug 2026 to Nov 2026

Node.js, Express 5, Apache Kafka 3.7 (KRaft), KafkaJS, PostgreSQL 16, Drizzle ORM, Docker Compose, k6, JWT

SSituation

Per-message Postgres transactions capped consumer throughput at 48/s and piled up lag

While the original Transactional Outbox avoided dual writes, profiling revealed that sequential `eachMessage` consumers spent 98.2%–99.7% of their time on per-message PostgreSQL round trips—capping 100-VU fulfillment at 48.42 checkouts/s with 7,420 messages of lag (154.33s catch-up). Meanwhile, shared `outbox_events` lacked partial indexes for order/email topics, a single poison message could stall an entire partition, and the API Gateway opened a new TCP socket on every proxied request.

Baseline constraints before the refactor
  • Baseline `eachMessage` order consumer took 24.22ms/msg under load (91.2% atomic SQL tx + 8.4% idempotency SELECT)
  • API Gateway without HTTP keep-alive opened 4,405 TCP connections for 4,396 proxied requests (141.57 opens/s)
  • Published rows for order-successful and email-successful accumulated unbounded (>93k rows) without topic-scoped indexes/pruning
  • Checkouts must keep succeeding (HTTP 200) even when Kafka is completely down

Per-Message eachMessage Commits

48.42 /s Cap
Consumer Pipeline7,420 Lag @ 30s
24.22ms/msg (99.7% Postgres I/O)
154.33s lag catch-up

SKIP LOCKED & eachBatch + DLQ

375.75 /s (+7.76×)
1 SQL Tx / Batch0 msgs lag @ 30s
Poison pills isolated to payment-successful.DLQ
0.31s catch-up · 4/4 CI tests

Sequential 1-message DB transactions versus SKIP LOCKED relays and single-transaction eachBatch consumers.

TTask

Eliminate consumer lag, isolate poison pills, and prove resilience in CI

Instrument and remove the Postgres transaction bottleneck across all downstream consumers, add SKIP LOCKED batched outbox relays with topic-scoped pruners, implement 1-by-1 poison-pill DLQ fallback, split liveness from relay readiness, and verify every failure mode in GitHub Actions.

0 lag across all 3 services

Batch Consumer & Relay Pipeline

Convert order, email, and analytic consumers to idempotent eachBatch (1 SQL tx per batch via processed_events) and batch KafkaJS outbox sends with SKIP LOCKED.

4 automated CI fault tests

Poison-Pill & Crash Fault Isolation

Roll back failed batches cleanly, replay 1-by-1 in offset order, route only poison payloads to payment-successful.DLQ after 3 retries, and survive mid-batch SIGKILL.

HTTP 200 during Kafka outage

Ingress Keep-Alive & Split Health

Enable HTTP keep-alive in api-gateway, enforce 32+ char JWT_SECRET startup validation, and separate GET /health (200) from GET /relay-status (503).

AAction · Architecture & Implementation

SKIP LOCKED relays and eachBatch consumers guarantee zero-loss throughput

API Gateway validates JWTs over keep-alive connections into Payment Service, which commits payments and outbox rows atomically. SKIP LOCKED relays batch-publish to KRaft Kafka, feeding idempotent eachBatch consumers with DLQ isolation.

Architecture components
Keep-Alive GatewayEnforces 32+ char JWT_SECRET & reuses backend TCP sockets.
api-gateway/config.js
const MIN_JWT_SECRET_LENGTH = 32;
const secret = process.env.JWT_SECRET;
if (typeof secret !== "string" || secret.trim().length < MIN_JWT_SECRET_LENGTH) {
throw new Error(
`Missing or invalid JWT_SECRET: must be set and at least ${MIN_JWT_SECRET_LENGTH} characters long`
);
}
export const JWT_SECRET = secret;

Note: Fails fast on startup if JWT_SECRET is missing or short—eliminating insecure hardcoded defaults across gateway and CI.

Explanatory figures & telemetry

Measured system behavior across benchmarks and fault injections

Figure 1

Why Single-Partition eachMessage Plateaued: Per-Message Latency Anatomy

Total Per-Message Latency (Under Load)24.22 ms
Atomic DB Transaction (orders + processed_events + outbox)

p50 17.14ms · p95 50.54ms (commit + WAL fsync per message)

22.10 ms(91.2%)
Idempotency SELECT (processed_events lookup)

p50 1.62ms · p95 3.35ms

2.04 ms(8.4%)
CPU / JSON Parse / JS Overhead

p50 0.08ms · p95 0.12ms (JWT verify separately measured at 21.9 µs)

0.08 ms(0.3%)
Implied 1-Part Ceiling41.3 – 51.8 /s

Matches measured baseline_consumer 100-VU rate of 48.42 completed/s.

Master Gateway TCP Probe4,405 opens

4,396 reqs opened 4,405 TCP sockets (1:1) before enabling HTTP keep-alive.

Low-Contention Baseline13.42 ms/msg

Even idle, 10.77ms DB tx + 2.40ms SELECT capped 1 partition at ~75–90/s.

High-resolution performance.now() breakdown inside order-service eachMessage (N=500 under load). 99.7% of processing time was PostgreSQL I/O, not Node.js CPU.PHASE1-BENCHMARKS.md · benchmarks/measure-consumer-breakdown.mjs
Figure 2

Full-Drain Consumer Optimization: Completed Checkouts/s & Lag @ 30s

baseline_consumer (1 part, eachMessage)48.42 /s

7,420 lag @ 30s · 154.33s catch-up · p50 245.14ms

fix_a (6 parts, concurrency=6)87.88 /s (+1.81×)

7,912 lag @ 30s · 97.92s catch-up · p50 205.64ms

fix_b (1 part, eachBatch 1-tx/batch)375.75 /s (+7.76×)

0 lag @ 30s · 0.31s catch-up · p50 178.47ms

3-run mean across 20, 50, and 100 k6 VUs (1,000 distinct JWTs) drained completely to consumer lag = 0 on Ryzen 7 6800H / Docker WSL2.PHASE1-BENCHMARKS.md · summary-experiment-{baseline_consumer,fix_a,fix_b}.json
Figure 3

eachBatch Atomic Commit & 1-by-1 Poison-Pill DLQ Fallback

1. Bulk Dedupe
processed_events IN query

Single inArray() lookup + within-batch Set filter

Skips redeliveries cleanly after SIGKILL
2. Batch Commit
db.transaction() (1 per batch)

Bulk INSERT orders + processed_events + outbox_events

375.75 checkouts/s on 1 partition (FIFO preserved)
3. Poison Fallback
processSingleOrderMessage()

If batch tx fails, rolls back & replays 1-by-1 in offset order

49/49 valid orders commit without halting
4. DLQ Isolation
payment-successful.DLQ

After 3 retries, sends only poison payload with error headers

Follow-up msg #51 processes; Kafka lag = 0
Fault path:
SIGKILL after DB batch tx commit, before Kafka resolveOffset() → Partition redelivers 50 messages on container restart → processed_events PK skips all 50; 0 duplicates, lag = 0
Verified in CI by test-poison-batch.js (49 valid + 1 null-userId + follow-up #51) and test-mid-batch-crash.js (SIGKILL before offset commit).order-service/consumer-processor.js · .github/workflows/ci.yml
Action · Trade-offs

Four architectural choices that delivered 7.76× throughput

Action · Bugs fixed

Four production & benchmark bugs caught and fixed

Five consumer and relay env vars silently defaulted inside Docker

5c7f584
Symptom

Benchmarks showed sequential sends even when RELAY_BATCH_SEND=true was set on the host.

Cause

docker-compose.yml omitted RELAY_BATCH_SEND, CONSUMER_MODE, and OUTBOX_RETENTION_HOURS; payment pruner also passed raw JS Date to SQL.

Fix

Wired all env vars through Compose, fixed pruner SQL, and logged [EFFECTIVE CONFIG] at container boot.

Hardcoded JWT_SECRET fallbacks risked running insecure container defaults

d7069ab
Symptom

Gateway booted with fallback secrets when environment variables were unset.

Cause

Token signing and verification used inline || fallback strings across files.

Fix

Centralized 32+ char JWT_SECRET startup validation in api-gateway/config.js and auto-generated ephemeral CI secrets.

API Gateway opened a new TCP socket for every proxied request

51cc87c
Symptom

20-VU probe recorded 4,405 TCP ActiveOpens for 4,396 HTTP requests (141.57 opens/s).

Cause

Omitting an HTTP Agent in http-proxy-middleware defaulted to agent: false.

Fix

Configured persistent HTTP keep-alive agent, raising 50–100 VU ingress throughput past 370 req/s.

Kafka outage caused healthcheck failures during startup

77e9b9c
Symptom

payment-service failed health checks if booted while Kafka was offline.

Cause

Producer connection failure stalled startup instead of retrying with backoff behind split health endpoints.

Fix

Added exponential Kafka connect backoff and separated /health (200) from /relay-status (503).

100-VU Completed Checkouts
Before:48.42 /s · 7,420 lag @ 30s · 154.33s catch-up
After:375.75 /s (+7.76×) · 0 lag @ 30s · 0.31s catch-up
fix_b (PHASE1-BENCHMARKS.md)
Email & Analytic Lag (100 VUs)
Before:5,050 email msgs (44s) + 20,480 analytic msgs (97s)
After:0 msgs / 0.00s catch-up across all 3 downstream services
Full-pipeline benchmark
CI Fault-Tolerance Matrix
Before:Unverified crash recovery & un-isolated bad payloads
After:4/4 live Docker Compose resilience scripts green in GitHub Actions
.github/workflows/ci.yml
Roadmap

Split `outbox_events` into isolated per-service database schemas for independent horizontal DB scaling and run isolated causal measurements on `RELAY_BUSY_PAUSE_MS`.