Apache Kafka
3.xSummary
Distributed event streaming platform designed for high-throughput, fault-tolerant, ordered, and durable log-based messaging between producers and consumers.
Primary Use Case
Event streaming pipelines, change data capture (CDC) transport, log aggregation, real-time analytics ingestion, and decoupling of high-throughput producers from consumers.
Workload Fit
Strengths
Best for
- ·High-throughput event pipelines requiring durable ordered delivery
- ·CDC-based replication between systems (database to analytics, microservices)
- ·Decoupling producers from consumers at scale (fan-out, fan-in)
- ·Event sourcing as the persistent event log
Excels when
- ·Write throughput exceeds what a message queue can sustain
- ·Consumers need to replay historical events (retention-based reprocessing)
- ·Multiple independent consumers need the same event stream
- ·Team can commit to the operational investment required
Architectural advantages
- ·Persistent, replayable log enables consumer catch-up and event replay
- ·Partition-based horizontal scaling decouples producer throughput from consumer rate
- ·Log compaction enables event sourcing with storage efficiency
- ·Strong ordering guarantee per partition enables deterministic event processing
When to Avoid
Avoid when
- ·Workload needs <1ms end-to-end latency: Kafka trades latency for throughput
- ·Team size or maturity cannot support Kafka's operational complexity
- ·Message volumes are low enough that a simple queue (RabbitMQ, SQS) suffices
Common misuses
- ·Using Kafka as a work queue for tasks that don't need replay: operational overhead exceeds value
- ·Under-partitioning topics at launch: adding partitions later breaks key-based ordering
- ·Treating Kafka as a database for querying: it is a log, not a query engine
Consistency & Transactions
Scaling
Read scalability
Consumer groups read partitions in parallel. Adding consumers up to partition count scales read throughput linearly. Kafka Connect and Kafka Streams provide consumer-side parallelism beyond raw consumer groups.
Write scalability
Topics are partitioned across brokers. Write throughput scales horizontally by adding partitions and brokers. Single-partition throughput is bounded by disk I/O and network; multi-partition topics scale to millions of messages/second.
Failure Behavior
Known failure modes
- ·Unbalanced partitions: hot partitions saturate individual brokers
- ·Consumer lag accumulation: slow consumers fall behind and cannot catch up
- ·Replication under-replication: loss of broker can drop ISR below min.insync.replicas
- ·Log compaction delay: compaction lag causes unbounded topic size growth
Bottlenecks
- ·Single-partition throughput bounded by broker disk I/O (~200MB/s per partition)
- ·Consumer lag accumulation when consumers cannot keep pace with producer rate
- ·ZooKeeper (pre-3.x) / KRaft metadata operations add coordination latency
Degradation patterns
- ·Under-replicated partitions when broker falls behind ISR: risk of data loss on broker failure
- ·Log compaction lag causes topic size growth proportional to update frequency
- ·Consumer group rebalance storms under rapid consumer add/remove cause processing pauses
Recovery considerations
- ·min.insync.replicas=2 and acks=all required for durability guarantee: default acks=1 can lose data
- ·Consumer lag recovery requires catch-up processing: cannot skip to head without message loss
- ·Broker replacement requires partition rebalancing: monitor ISR restoration time
Operational Pitfalls
- ·Under-partitioned topics: adding partitions later breaks ordering guarantees for keyed messages
- ·Not monitoring consumer lag: silent consumer delays go undetected until they become incidents
- ·Infinite retention without disk planning: uncapped topic growth exhausts broker disk
- ·At-least-once without idempotent consumers: duplicate processing causes data corruption
Architecture Guidance
Common topology roles
Migration notes
- ·From RabbitMQ: Kafka semantics differ: persistent ordered log vs transient queue; consumers must be redesigned
- ·Replacing Kafka with a managed alternative (Redpanda, Pulsar): validate partition semantics and consumer group API compatibility
- ·Adding Kafka to an existing synchronous system requires consumer lag budget planning and backpressure handling
Advisor Guidance
When: scenario uses Kafka for event streaming or CDC
Set min.insync.replicas=2 with acks=all; monitor consumer lag as primary health signal
When: scenario has team_maturity below senior
Kafka operational complexity requires dedicated expertise: consider MSK or Confluent Cloud to reduce ops burden
When: scenario uses Kafka for low-volume task queues
Kafka is overengineered for simple work queues at low volume: evaluate RabbitMQ or SQS for simpler operational model
Comparison Factors
operational complexity
High: broker management, partition tuning, consumer group coordination, and monitoring required
throughput
Very high: millions of messages/second across a well-sized cluster
latency
Tens of milliseconds: optimized for throughput, not latency
team maturity required
Senior: Kafka incidents require deep understanding of partition replication and consumer group semantics
Managed Cloud Options
Enables Patterns
Basis
Mature, widely deployed technology. Operational characteristics well-documented across industry. Complexity is high but well-understood at scale.
Learning Modules
Evolving Architecture Without Breaking Production
How to migrate production systems incrementally using strangler fig, expand-contract schema changes, traffic shadowing, and online schema change tools: without big-bang rewrites, downtime, or data loss.
Audit Logging and Traceability
How audit logs differ from application logs, what every audit entry must contain, how to design an immutable append-only audit store, and the operational patterns for querying, partitioning, and securing audit data at scale.
CAP Theorem and PACELC
Why distributed systems cannot simultaneously provide consistency, availability, and partition tolerance: and how PACELC extends this to the latency-consistency tradeoff that applies even when the network is healthy.
CQRS Operational Tradeoffs
How separating the command and query models enables independent scaling, what consistency guarantees CQRS gives up, how read model staleness propagates, and when the operational complexity is justified.
Event Sourcing
Store a sequence of immutable domain events as the source of truth; derive current state by replaying the event log. Understand projections, snapshots, event versioning, and the operational tradeoffs that make event sourcing correct in some systems and wrong in others.
Kafka Consumer Lag
How Kafka consumer groups track offsets, how consumer lag accumulates when processing falls behind production, how uneven partition assignment creates lag skew, and how to instrument and remediate consumer lag before it causes data pipeline delays.
Partition Hotspots
How partition key design determines load distribution, how sequential keys create hotspot partitions, why hotspots cause cascading failures, and how to design partition keys that distribute load uniformly.
Queue Backlog Propagation
How message queues build backlogs under producer surges, how consumer lag propagates downstream, how unbounded queues become memory bombs, and how backpressure prevents cascade failures.
Evolution Paths
Modular Monolith → Event-Driven Services
Modular Monolith → Event-Driven Services
OLTP Analytics Queries → OLTP + OLAP Separation
Unified OLTP + Analytics on PostgreSQL → Separated OLTP (PostgreSQL) + OLAP (ClickHouse/Snowflake)
RabbitMQ → Kafka
RabbitMQ Message Queue → Kafka Event Stream
Simulations
Related Architecture Knowledge
Outbound: this entity affects
Kafka consumer groups are the canonical implementation of the competing consumers pattern. Each consumer group member is assigned an exclusive subset of topic partitions, ensuring each message is processed by exactly one consumer within the group while enabling horizontal scaling up to the partition count.
Tradeoffs
- ·Partition ceiling bounds parallelism; over-partitioned topics add controller overhead
- ·Rebalancing pauses processing; eager vs cooperative rebalancing protocols trade pause duration for complexity
- ·At-least-once delivery requires idempotent consumers to handle redelivery on rebalance
Kafka guarantees ordering within a partition but not across partitions; if events for the same entity are routed to different partitions, consumers may process them out of causal order.
Full relationship →Kafka consumer groups implement backpressure via the consumer poll loop: pausing the poll loop stops consumption without dropping messages, providing durable backpressure to the producer.
Full relationship →Kafka topics serve as the delivery mechanism for fat event payloads; Kafka's compacted topics can retain the latest state per key, enabling exactly the event-carried state transfer pattern.
Full relationship →Kafka's durable, ordered, append-only log is the canonical infrastructure for an event store at scale. Topics with compaction or retention policies serve as the persistent event log that event sourcing requires.
Tradeoffs
- ·Kafka does not support optimistic concurrency at the aggregate level natively: application must enforce sequence numbers
- ·Event replay for a single aggregate requires filtering a partition by aggregate_id: not as efficient as a database query by aggregate_id
- ·At-least-once delivery requires idempotent projection handlers
Kafka is the standard downstream target for WAL-based CDC pipelines: Debezium captures database WAL records and publishes them to Kafka topics, which downstream consumers process to maintain derived data stores, caches, and event-driven services.
Tradeoffs
- ·Debezium replication slot holds WAL until consumed: disconnected Debezium can fill primary disk
- ·CDC events are row-level operations: application-level event semantics require transformation in a stream processor
- ·Ordering guarantees are per-partition only: cross-table ordering requires careful partition key strategy
Inbound: affects this entity
Temporal handles durable workflow orchestration and long-running state machines; Kafka handles high-throughput event streaming. They complement each other when workflows react to Kafka events or emit events on completion.
Full relationship →Used In Architecture Scenarios
AI / RAG Application
A Retrieval-Augmented Generation (RAG) architecture that combines vector similarity search for semantic document retrieval with relational metadata filtering, using PostgreSQL with pgvector as the unified store for both embeddings and structured data. Redis provides a semantic cache to avoid redundant embedding model inference and reduce vector index query load for repeated or similar queries. Kafka manages the asynchronous embedding generation pipeline that keeps the vector index current as source documents are added or updated.
Multi-Tenant SaaS
A multi-tenant API gateway providing authentication, distributed rate limiting, request routing, payload transformation, and per-tenant usage analytics for API publishers. The hot path: authentication check, rate limit evaluation, and routing decision: must complete in under 1ms using Redis-only data structures to avoid proxying latency dominating upstream service response time. PostgreSQL stores tenant configuration, subscription plans, and API key definitions. Kafka receives API usage events for downstream billing and analytics. Configuration changes (rate limit updates, routing rule edits) must propagate to all gateway replicas without restart.
Analytics Pipeline
An OLAP-oriented analytics architecture that ingests operational changes from PostgreSQL via WAL-based CDC into Kafka, then routes them to a columnar analytics store (ClickHouse or Snowflake) for product analytics, business intelligence, and operational reporting. The CQRS separation ensures analytical queries never degrade transactional write performance, and materialized views provide pre-aggregated query acceleration for the most expensive analytical patterns.
Financial Ledger
An append-only audit log architecture for capturing system actions: user operations, data access events, configuration changes, and financial operations: with cryptographic integrity chaining, immutable storage, and dual-path query serving. PostgreSQL stores the authoritative append-only event log in time-partitioned tables; ClickHouse serves historical aggregate queries and retention analytics; Kafka streams audit events in real time to SIEM integrations and security dashboards; Redis caches hot audit query results for compliance-facing read paths. No record is ever updated or deleted: only inserts are permitted. Each record includes a hash of the previous record, forming a tamper-evident chain verifiable without external tooling.
Multi-Tenant SaaS
A multi-tenant developer tooling platform providing CI/CD pipeline execution, log aggregation, code analysis, and dependency scanning across isolated tenant organizations. Tenant isolation is the primary correctness constraint: a security boundary violation between tenants is a critical incident, not a performance event. PostgreSQL row-level security enforces data isolation; Redis manages job queues and distributed locks; Elasticsearch indexes pipeline log output for search; Kafka delivers webhook events to tenant-registered endpoints; MinIO stores pipeline artifacts. Resource quota enforcement prevents any single tenant's burst from affecting others.
Write-Heavy Application
A durable background job execution platform where jobs are enqueued via API and executed by competing consumer worker pools. PostgreSQL is the durable job store, job definitions, retry state, scheduling metadata, and dead-letter records persist in PostgreSQL with ACID guarantees, surviving any worker or queue infrastructure failure. Redis tracks in-flight job state (which worker claimed which job, visibility timeout lease expiry) to enable fast lease checks without PostgreSQL queries on the hot path. Temporal provides workflow orchestration for multi-step jobs that require coordination across multiple execution stages, with built-in state machine semantics and durable activity execution. Kafka carries job completion events to downstream consumers (analytics, billing triggers, notification fan-out). Backpressure between the job enqueue rate and worker execution rate prevents runaway job accumulation when workers are degraded.
Marketplace Platform
An e-commerce order lifecycle platform handling cart, checkout, payment, fulfillment, and returns across a mixed read/write workload where product discovery is read-heavy, checkout is write-transactional, and fulfillment is event-driven. The saga pattern orchestrates multi-step checkout: reserve inventory → charge payment → confirm order → notify fulfillment. PostgreSQL owns order records and inventory with row-level locking; Redis holds session state and cart contents with sub-millisecond access; RabbitMQ delivers fulfillment notifications with dead-letter handling; Elasticsearch serves product search and order history with faceted navigation. CQRS separates the write command path from the read model: the order read model is denormalized for fast order history queries without joining across domain tables.
Event-Driven System
A streaming architecture that captures database changes via WAL-based CDC, publishes them to an event stream (Kafka), and routes them to analytics consumers. Decouples the write path from the read path while maintaining a durable, replayable event log.
Financial Ledger
A strict consistency financial architecture for double-entry accounting, payment processing, and audit trail management where every debit must have a corresponding credit, every state transition must be ordered and durable, and the complete history must be reconstructable without gaps. Event sourcing provides an append-only audit log; the outbox pattern guarantees at-least-once downstream event delivery without distributed two-phase commit (idempotent consumers deduplicate on event ID for effectively-once processing); PostgreSQL provides ACID guarantees for ledger entry atomicity.
Realtime Collaboration
An online multiplayer game backend built around authoritative server game state synchronization. Game rooms run as distributed state machines where the server is the single source of truth for game state: client predictions are reconciled against the server state at every tick. WebSocket connections provide low-latency bidirectional communication for state deltas. Redis stores active game room state (in-flight, with sub-millisecond access), session affinity tokens (routing players to the same server instance as their game room), and matchmaking queues. PostgreSQL is the durable store for player profiles, persistent inventory, leaderboards, and achievement records. Kafka carries post-game event streams for analytics, anti-cheat processing, and achievement evaluation. NATS provides low-latency pub/sub for intra-cluster game state broadcasting when multiple game server instances must coordinate on shared state. Event sourcing records every game action as an immutable event for replay, dispute resolution, and anti-cheat audit.
Realtime Collaboration
A real-time location tracking platform for moving entities: vehicles, delivery couriers, field workers, and assets: receiving position updates at 1–30 second intervals from thousands of simultaneously tracked objects. Redis geospatial indexes (GEOADD / GEOSEARCH) serve sub-10ms proximity queries against the live position surface; PostgreSQL stores durable entity metadata and historical location records; TimescaleDB stores high-frequency time-series location data with automatic hypertable chunking and retention policies; Kafka streams location events to downstream consumers (dispatch systems, customer tracking apps, analytics pipelines). Geofence evaluation runs at ingestion time: each incoming position update is tested against active geofences for the entity's region, and geofence entry/exit events are emitted as Kafka messages to downstream consumers.
Financial Ledger
An electronic health record (EHR) architecture built around strict auditability, HIPAA compliance, and append-only correctness. Clinical records are mutable by design (amendments, addenda) but corrections must be explicitly attributed, not silently overwritten. Event sourcing provides a reconstructable audit log; PostgreSQL row-level security enforces patient-level access control at the database layer; Kafka streams HL7 FHIR events to downstream clinical systems. The architecture must support breach detection, access auditing, and state reconstruction at any historical point: not just current state retrieval.
Write-Heavy Application
A high-rate device telemetry ingestion architecture designed for millions of devices emitting metrics at 1–60 second intervals. Kafka absorbs device writes as an ingestion buffer, decoupling device-facing ingest endpoints from the storage write path so that downstream storage pressure never propagates back to devices. TimescaleDB provides time-series storage with automatic chunk partitioning by time range, native compression, and continuous aggregate views for rollup queries. ClickHouse serves as the OLAP layer for device fleet analytics queries. Redis caches last-known device state (current readings per device) for real-time alerting queries that must not scan historical storage. Backpressure on the Kafka consumer side prevents storage write throughput from being overwhelmed by burst ingestion events from device reconnect storms.
AI / RAG Application
A low-latency feature serving platform for ML model inference, providing both batch (offline) and real-time (online) feature access with strict training-serving consistency. Redis serves the hot feature cache with p99 latency targets below 5ms for online inference requests; PostgreSQL provides point-in-time feature lookups for offline training jobs with temporal consistency guarantees; Cassandra stores high-cardinality feature entities at write scale beyond PostgreSQL's single-primary ceiling; Kafka streams feature computation events from online feature pipelines to update the cache; Qdrant stores vector features for embedding-based model inputs and similarity lookups; ClickHouse serves feature analytics and drift monitoring across training dataset populations. Feature versioning is first-class: every feature value is tagged with a pipeline_version and computed_at timestamp to support model reproducibility and training-serving skew diagnosis.
Event-Driven System
A multi-channel notification delivery architecture that accepts upstream business events (order placed, payment received, comment posted, threshold alert triggered) and routes them to per-channel delivery workers (push via FCM/APNs, email via SendGrid, SMS via Twilio, in-app via WebSocket). Kafka carries raw business events from upstream producers. RabbitMQ handles per-channel fan-out with separate exchanges and queues per delivery channel, isolating email queue backlog from push notification delivery. PostgreSQL provides durable notification state tracking (sent, failed, bounced, suppressed). Redis enforces per-user rate limiting (notification frequency caps to prevent fatigue) and stores deduplication tokens to prevent duplicate sends across retry attempts. The inbox pattern on the consumer side ensures idempotent delivery even when Kafka produces duplicate events.
Analytics Pipeline
A metrics, logs, and traces ingestion and query platform built to absorb the telemetry output of a production system fleet: including the telemetry volume spikes that accompany the incidents the platform is meant to detect. ClickHouse stores metrics data with automatic time-based rollup via continuous materialized views; TimescaleDB provides complementary time-series storage for high-cardinality alert evaluation; Kafka buffers the ingestion stream against downstream write pressure, decoupling ingest acceptance rate from storage write throughput; Elasticsearch serves log full-text search and structured field filtering; Redis caches dashboard query results and active alert state for sub-100ms alert evaluation latency. The alert engine evaluates threshold and anomaly rules against pre-computed materialized views, not raw data, to bound alert evaluation cost independent of ingestion volume.
Event-Driven System
A social activity feed architecture where user actions (posts, likes, comments, follows) fan out asynchronously to follower timelines. Redis stores hot feed data as pre-materialized lists per user, enabling O(1) timeline reads for the 99th percentile of users. Kafka carries fan-out work to async workers that write to follower Redis keys. PostgreSQL is the durable store for the social graph, posts, and user content. The system uses a hybrid fan-out model: fan-out-on-write for users with fewer than ~10,000 followers (low fan-out cost), fan-out-on-read for high-follower celebrity accounts where pre-materialized fan-out would saturate workers and Redis write bandwidth.
Event-Driven System
A video and audio streaming architecture where content ingestion triggers an async multi-variant transcoding pipeline, CDN delivery handles 95%+ of playback traffic, and Cassandra absorbs the write volume of per-user viewing history. Kafka decouples upload events from transcoding workers; MinIO stores raw and encoded assets; Redis maintains playback session state and view counters. The architecture must handle upload spikes without blocking delivery, and cache cold starts without cascading database load.
Marketplace Platform
A two-sided marketplace architecture serving buyers, sellers, listings, transactions, search, and notifications from a shared infrastructure, where multiple independent domains must coordinate without tight coupling. Event sourcing captures every state transition; the saga pattern orchestrates multi-step transactions (create order, reserve inventory, charge payment, notify seller) with compensating transactions for partial failures. Kafka decouples domain event publication from consumption; RabbitMQ handles notification fanout; Elasticsearch serves listing search; Redis caches listing display and session state.
Write-Heavy Application
A high-volume transactional write architecture anchored on PostgreSQL, where write throughput, durability guarantees, and audit completeness must coexist. The outbox pattern ensures reliable event publishing to Kafka without two-phase commit, and WAL-based CDC provides a durable change log that can reconstruct system state. Connection pooling via PgBouncer bounds connection overhead at the database layer.