HomeBlogHow to Build an Event-Driven Architecture...

Engineering Guide · 9 min read · May 28, 2026

How to Build an Event-Driven Architecture Using Kafka

Apache Kafka solves real problems—high-throughput event streams, multi-consumer fan-out, and durable replay—but deploying it prematurely slows lean engineering teams down. This CTO guide details when Kafka beats simpler queues, how the transactional outbox prevents lost events, and how partition keys and idempotent consumers keep state consistent.

Author
Smit Desai
Published
May 28, 2026
Read time
9 min read
Topic
Data & Databases
Services
Custom Web · Mobile Apps · All Services

Few infrastructure proposals divide engineering leadership as sharply as Apache Kafka. On one side sits a growing product held together by brittle synchronous webhooks and nightly cron sweeps that drop updates whenever a downstream worker restarts. On the other sits a six-engineer team losing an entire quarter to consumer group rebalances, schema compatibility breaks, and partition skew when a straightforward job queue would have shipped in two days.

Across 170+ backend builds and rescues since 2017, the clearest filter for CTOs comes down to one architectural question: do your services require a durable, replayable, multi-subscriber commit log—or simply asynchronous task dispatch? When the log genuinely earns its keep, a handful of structural patterns prevent silent data loss and operational thrash.

Kafka vs. Standard Queues: Know What You Are Buying

Classic brokers (AWS SQS, RabbitMQ, Redis job queues) discard a message once a worker acknowledges completion. Kafka operates as a partitioned, append-only disk log. Each consumer group tracks its own read offset independently—allowing billing, audit archiving, warehouse sync, and notification services to read identical domain facts at different speeds, and even rewind seven days back to rebuild a corrupted projection.

Architectural Dimension Redis Queues / Streams Cloud Queues (SQS + SNS) Apache Kafka (MSK / Confluent)
Storage Model In-memory worker queue / stream Managed queue with pub-sub fan-out Persistent partitioned commit log
Replay Capability Constrained by RAM capacity Deleted on ACK (14-day max unacked) Days or weeks on disk; arbitrary rewind
Ordering Semantics Single stream per consumer FIFO queues (throughput ceiling) Per-partition strict order at scale
Ops Footprint Minimal (standard app infra) Negligible (fully serverless) Substantial (lag, partitions, schemas)
Best Fit Workload Mailers, PDF generation, webhooks Light service decoupling < 10k msg/s CDC, metering, multi-team event backbone

If your immediate bottleneck is slow API endpoints or simple background retries, inspect Redis Streams primitives or managed cloud queues before taking on broker operations.

Eliminating Dual-Write Races With a Transactional Outbox

The earliest bug in almost every new event pipeline hides inside the first producer service:

Step 1: BEGIN; UPDATE shipments SET state = 'dispatched'; COMMIT;
Step 2: kafka.produce("shipments.lifecycle", eventPayload)  <-- Fails on broker timeout!

When Step 2 drops after Step 1 commits, warehouse records show dispatched while customer notifications never fire. Reordering the calls creates the inverse hazard: broadcasting a dispatched event before COMMIT leaks phantom state if a foreign-key constraint rolls back PostgreSQL.

Atomic Mutations via Outbox Tables

Record the domain event inside an event_outbox_queue table within the exact same SQL transaction as the business update. A separate relay process—or log-based CDC connector such as Debezium—polls or streams pending rows into Kafka safely:

CREATE TABLE event_outbox_queue (
    event_seq BIGSERIAL PRIMARY KEY,
    event_uid UUID NOT NULL UNIQUE,
    domain_entity VARCHAR(48) NOT NULL,   -- e.g. 'shipment'
    partition_key VARCHAR(64) NOT NULL,   -- entity ID for partition routing
    event_name VARCHAR(96) NOT NULL,      -- e.g. 'shipment.dispatched.v1'
    body_json JSONB NOT NULL,
    enqueued_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    dispatched_at TIMESTAMP WITH TIME ZONE NULL
);

CREATE INDEX idx_event_outbox_pending
    ON event_outbox_queue (event_seq)
    WHERE dispatched_at IS NULL;

Pairing partial indexes with PostgreSQL transaction atomicity (see PostgreSQL performance tuning guidance) delivers at-least-once publishing without distributed two-phase commit overhead.

Partition Keys, Producer Durability, and Versioned Envelopes

Once events flow into topics, stream integrity depends on three defaults established before engineering teams create topic #2.

Pick Partition Keys for Entity Ordering, Not Skew

Kafka preserves order strictly inside one partition. Supply partition_key (such as shipment_id or account_id) so created, paid, and refunded stay sequenced on the same partition. Never partition by low-cardinality fields like region or plan_tier; doing so pins massive load onto two partitions while leaving the rest idle.

Standardize Producer Safety Settings

Wrap every message in an explicit envelope carrying event_uid and schema_version, and configure topics and producers against silent ack loss:

# Production baseline for durable business event topics
topic_policy:
  replication.factor: 3
  min.insync.replicas: 2
  retention.ms: 604800000    # 7-day replay buffer

producer_defaults:
  acks: "all"                # Require leader + ISR write confirmation
  enable.idempotence: true   # Deduplicate network-retry writes at broker
  retries: 2147483647
  delivery.timeout.ms: 120000
  compression.type: "zstd"

Combining acks: "all" with min.insync.replicas: 2 guarantees an acknowledged write survives an unexpected single-broker failure.

Building Idempotent Consumers and Dead-Letter Flows

Even with broker-side producer idempotence enabled, outbox relay restarts and consumer group rebalances guarantee that downstream consumers will see duplicate deliveries. Assuming exactly-once execution inside consumer code guarantees double-billing bugs.

Consumer-Side Deduplication Inside the Local Transaction

Write event_uid into a consumed_event_log table inside the same local transaction that mutates consumer state. When ON CONFLICT DO NOTHING affects zero rows, skip side effects and commit the Kafka offset:

INSERT INTO consumed_event_log (event_uid, group_name, handled_at)
VALUES ($1, 'ledger-worker', CURRENT_TIMESTAMP)
ON CONFLICT (event_uid, group_name) DO NOTHING;
-- Proceed with local state mutation only when 1 row is inserted

Routing Poison Pills Without Halting Partitions

If an unexpected JSON shape triggers an unhandled crash and the consumer refuses to advance its offset, every customer sharing that partition stalls behind one broken message. Protect availability with three guardrails:

  1. Bounded fast retries (2–3 short attempts) for transient deadlocks or brief downstream timeouts.
  2. Dead Letter Topic forwarding (*.dlq) capturing original bytes, headers, and stack context before advancing the offset so healthy traffic resumes immediately.
  3. Lag-based alerting monitoring records-lag-max per consumer group so engineering catches stalled workers within minutes rather than learning from support tickets.

Preserving Tenant Context in Async Workers

Background Kafka consumers run outside web middleware. Embed tenant_id and actor_id inside every event envelope and enforce scoped queries at the repository layer—matching the isolation patterns detailed in our multi-tenant SaaS guide.

Phased Rollout Strategy for Engineering Leaders

Skip big-bang microservice rewrites. Extract one clear asynchronous boundary first—such as usage metering, audit logs, or billing webhooks—running on managed Kafka (Confluent Cloud, AWS MSK, or Redpanda) backed by outbox tables and strict DLQ alerts. Prove replay runbooks in production before adding a second domain stream.

If your team is decoupling a legacy monolith through software modernization and upgrades or needs hands-on capacity to build outbox relays and resilient consumers, SmitDev embeds directly with CTOs—at $55/day (8–9 hours of daily engineering) or $1,999/month for continuous delivery. Explore dedicated engineering support or contact us to review your event topology.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Infrastructure Proof

300+ WordPress & Cloud Server Fleet

From server-level management of 300+ WordPress sites for a Finland client to PostgreSQL query tuning (3,982 -> 52 queries).

Pillar 2 · Legacy Rescue

Upgrade Old Software (10 Hrs Free)

Audit bottlenecks, eliminate security vulnerabilities, and stabilize production servers—starting with 10 free engineering hours.

01 — Frequently asked questions

data & databases

When does a technical organization actually need Apache Kafka over Redis or AWS SQS?

Adopt Kafka when you need multiple independent services consuming the same event stream at their own pace, strict ordering per entity key at high throughput, or durable log replay to rebuild downstream read models and audit trails days or weeks later.

What happens if an application writes to PostgreSQL and publishes to Kafka in the same request?

You create a dual-write race condition. If PostgreSQL commits and Kafka times out, downstream services never learn about the change; if Kafka succeeds and PostgreSQL rolls back, consumers process a ghost event. Always use the transactional outbox pattern.

How does Kafka guarantee message ordering without bottlenecking throughput?

Kafka guarantees strict ordering only within a single topic partition, not globally across a topic. By using an entity identifier such as tenant_id or order_id as the partition key, all events for that entity land on the same partition in exact order while different entities scale horizontally.

How should engineering teams handle poison-pill messages that crash Kafka consumers?

Never block a partition infinitely on a malformed payload. Retry transient errors with bounded backoff, then route unprocessable messages with error metadata to a Dead Letter Topic (DLT) and commit the offset so healthy traffic continues flowing.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.