From Monolith to 13 Microservices: Redis Idempotency and BullMQ Under Load
Pragmatic criteria for decomposing a monolith into 13 decoupled services, persist-before-enqueue ingestion, Redis idempotency keys, BullMQ Dead Letter Queues, and sustaining velocity with 295+ automated tests.
Splitting a monolith into microservices for resume-driven reasons is the fastest way to trade function calls for network latency and distributed debugging headaches. Yet when a production platform mixes millisecond-SLA webhook ingestion, multi-second AI agent turns, catalog syncing, messaging channel adapters, and billing workflows inside one process, a spike in one workload inevitably starves everything else.
In this engineering note, I break down how we evolved into a 13-service topology without stalling delivery: our strict criteria for extracting a service, how we guarantee idempotency using Redis and BullMQ so network retries never cause duplicate side effects, how Dead Letter Queues keep failures observable, and how 295+ automated tests keep refactoring safe.
When migrating from a monolith to microservices actually pays off
We run every extraction proposal through three concrete filters. First is workload heterogeneity: when an ingestion endpoint must acknowledge Meta or Stripe webhooks in under 150 ms while an LLM worker takes 3 seconds per turn, isolating them protects edge tail latency.
Second is blast-radius containment: an out-of-memory crash or third-party rate limit inside a channel adapter or export worker should never take down core authentication or transactional APIs. Third is deployment cadence: external integration adapters evolve far more frequently than core billing tables. We only carve out a service when at least two of these filters hold true.
- Keep together: tightly coupled domain models requiring single-database ACID transactions.
- Extract into services/workers: webhook ingestion, channel adapters (WhatsApp, Discord, Instagram), AI inference, vector indexing, and notifications.
- Migration pattern: Strangler Fig behind an internal gateway so traffic shifts gradually with zero downtime.
Redis idempotency and the Persist-Before-Enqueue pattern
True exactly-once network delivery does not exist; resilient distributed systems pair at-least-once delivery with idempotent consumers. Webhook providers retry aggressively whenever a timeout or 5xx occurs. If your receiver executes business logic synchronously, a brief downstream slowdown spirals into retry storms and duplicate customer messages.
Our ingestion service separates acceptance from execution. After verifying the cryptographic signature, it acquires an atomic Redis idempotency lock (`SET key 1 NX EX 86400`), persists the raw payload into PostgreSQL guarded by `UNIQUE(provider, external_event_id)`, and enqueues a BullMQ job using that deterministic event ID as `jobId`. Total acceptance time stays under 35 ms.
import type { Redis } from "ioredis";
import type { Queue } from "bullmq";
import type { Pool } from "pg";
export interface InboundEvent {
provider: "whatsapp" | "stripe" | "instagram";
externalEventId: string;
tenantId: string;
payload: Record<string, unknown>;
}
export async function acceptWebhookEvent(
redis: Redis,
pg: Pool,
queue: Queue,
event: InboundEvent
): Promise<{ accepted: boolean; duplicate: boolean }> {
const dedupeKey = `idem:${event.provider}:${event.externalEventId}`;
// 1. Fast atomic deduplication in Redis (24h window)
const acquired = await redis.set(dedupeKey, "1", "EX", 86400, "NX");
if (acquired !== "OK") {
return { accepted: true, duplicate: true };
}
// 2. Durable persistence before enqueue (survives Redis restarts)
const { rowCount } = await pg.query(
`INSERT INTO inbound_events (provider, external_event_id, tenant_id, payload)
VALUES ($1, $2, $3, $4)
ON CONFLICT (provider, external_event_id) DO NOTHING`,
[event.provider, event.externalEventId, event.tenantId, JSON.stringify(event.payload)]
);
if (rowCount === 0) {
return { accepted: true, duplicate: true };
}
// 3. Deterministic BullMQ jobId prevents duplicate queue entries
await queue.add("process-inbound", event, {
jobId: `${event.provider}-${event.externalEventId}`,
attempts: 5,
backoff: { type: "exponential", delay: 2000 },
removeOnComplete: { age: 3600, count: 5000 },
removeOnFail: false,
});
return { accepted: true, duplicate: false };
}Retry policies, exponential backoff, and Dead Letter Queues
Blindly retrying every exception wastes worker capacity and obscures root causes. Transient failures—`429 Too Many Requests`, network resets, or upstream `503` responses—benefit from exponential backoff (2s, 4s, 8s, 16s, 32s). Permanent errors such as schema validation failures or revoked tenant credentials should fail fast via BullMQ's `UnrecoverableError`.
Whenever a job exhausts its retries or throws an unrecoverable error, a worker event handler archives the job metadata, correlation ID, error message, and payload into a Dead Letter Queue table and triggers an alert. Engineers can inspect the root cause, ship a fix, and replay affected events safely because downstream consumers are idempotent.
import { Worker, UnrecoverableError } from "bullmq";
export function createInboundWorker(connection: { host: string; port: number }) {
const worker = new Worker(
"inbound-events",
async (job) => {
const { tenantId, externalEventId, payload } = job.data;
if (!tenantId || !payload) {
throw new UnrecoverableError(`Invalid payload for event ${externalEventId}`);
}
// Idempotent domain processing
await processDomainEvent({ tenantId, externalEventId, payload });
},
{
connection,
concurrency: 12,
limiter: { max: 100, duration: 1000 },
}
);
worker.on("failed", async (job, err) => {
if (!job) return;
const exhausted = job.attemptsMade >= (job.opts.attempts ?? 1);
if (exhausted || err instanceof UnrecoverableError) {
await recordDeadLetter({
jobId: job.id ?? "unknown",
queue: "inbound-events",
payload: job.data,
error: err.message,
});
}
});
return worker;
}Sustaining velocity with 295+ automated tests across service boundaries
A 13-service topology without automated testing turns into a distributed big ball of mud within months. We structure our 295+ automated tests across three intentional layers: fast unit tests for pure domain rules and Zod schemas, container-backed integration tests verifying real PostgreSQL constraints, Redis `SET NX EX` locks, and BullMQ retry/DLQ transitions, and end-to-end contract tests exercising full webhook-to-worker flows.
Every pull request runs this gate in CI before merge. That discipline lets us upgrade dependencies, evolve event schemas, and deploy individual services multiple times a week without silent contract drift.
- Unit tests (~180): domain invariants, normalization, backoff calculations, and event serialization.
- Integration tests (~85): PostgreSQL unique constraints, Redis idempotency windows, and BullMQ DLQ routing.
- End-to-end contract tests (~30+): signed webhook ingestion through async worker completion.
Closing thoughts: decouple with discipline and observability
Microservices deliver real leverage when service boundaries match genuine scaling and fault-isolation needs—and when async queues are backed by strict idempotency and automated tests. If your team is scaling a distributed backend or hardening event queues, see our Microservices Architecture & High-Throughput Distributed APIs practice.
Next architectural step
Microservices Architecture & High-Throughput Distributed APIs
Want to apply this architecture in your stack? Reach out at info@artagdev.com.co or review the full deliverables of our dedicated service.