Event-Driven Architecture with Redis Streams, Kafka & Webhooks: Practical System Design Guide

In traditional monolithic and early microservice architectures, systems communicate primarily through synchronous Request-Response protocols such as REST over HTTP or gRPC. When a user checks out an order, the web service synchronously calls the Payment Gateway, waits for a response, calls the Inventory Service, waits again, calls the Shipping Service, and finally contacts the Notification API to send an email—all while the user’s browser is frozen waiting for the HTTP request to finish.

This synchronous design creates tight coupling and high fragility. If the notification service experiences latency, the checkout pipeline times out. If the inventory service goes down, the entire transaction crashes. In modern distributed cloud computing, this bottleneck is resolved through Event-Driven Architecture (EDA).

In an event-driven system, services communicate asynchronously by emitting and reacting to immutable state changes known as Events (e.g., OrderPlaced, PaymentCaptured, UserRegistered). In this architectural guide, we will examine the core tenets of Event-Driven Architecture, contrast ephemeral Pub/Sub with persistent event logs, compare Redis Streams vs. Apache Kafka, implement consumer groups with automatic error recovery, guarantee message idempotency, and design resilient Dead Letter Queues (DLQ).


Core Architectural Principles: Synchronous vs. Event-Driven

To understand the power of event-driven systems, contrast the two communication paradigms:

  • Synchronous (Coupled): The producer requires immediate execution and relies on the consumer being online and healthy. High temporal coupling means a failure in any single downstream dependency ripples backwards and fails the initial client request.
  • Asynchronous (Decoupled): The producer simply writes an event to an event log and immediately returns HTTP 202 Accepted or 200 OK to the client. Multiple downstream consumers process the event independently at their own pace. If a consumer is temporarily offline for deployment or maintenance, messages queue safely without data loss.

Pub/Sub vs. Event Streaming: The Crucial Difference

Engineers often conflate basic Message Pub/Sub with Event Streaming. While both decouple producers from consumers, their operational behaviors differ dramatically:

1. Ephemeral Pub/Sub (Redis Pub/Sub, RabbitMQ Fanout)

Traditional Pub/Sub operates on a fire-and-forget model. A message is broadcast to active subscribers currently connected to a channel. If a subscriber is disconnected due to a server restart or network glitch when the message is published, that message is permanently lost. Furthermore, historical messages cannot be replayed or audited.

2. Persistent Event Logs (Redis Streams, Apache Kafka)

Event Streaming utilizes an append-only, immutable commit log stored on disk or in persistent memory. Each event is assigned a monotonically increasing ID (offset). Consumers maintain their own cursor position within the log. If a consumer crashes, it resumes precisely where it left off. If you deploy a new microservice months later, it can replay the event log from the beginning of time to rebuild its database projection.


Redis Streams vs. Apache Kafka: Choosing the Right Engine

Both Redis Streams and Apache Kafka provide persistent, log-based event streaming with consumer groups. Choosing between them depends on your throughput scale and infrastructure complexity:

FeatureRedis StreamsApache Kafka
Storage MediumIn-Memory (RAM) with Disk Persistence (AOF/RDB)Sequential Disk / Page Cache (OS Level)
LatencySub-millisecond (< 1ms)Low millisecond (2ms – 10ms)
Throughput Capacity10,000 – 100,000 events/sec per node1,000,000+ events/sec per cluster
Operational OverheadVery Low (Built into standard Redis)High (Requires ZooKeeper/KRaft, JVM tuning)
Retention LimitBounded by RAM capacity (Capped streams via MAXLEN)Practically unlimited (Terabytes/Petabytes on cheap disk)
Best FitFast microservices, internal task queues, low latency eventsBig data pipelines, enterprise event hubs, multi-year replay

Production Implementation: Redis Streams with Consumer Groups

Let’s look at how to implement an event pipeline in Redis Streams using Consumer Groups. Consumer Groups allow multiple worker instances to divide events among themselves for horizontal scaling, while ensuring every message is acknowledged (ACKed).

Step 1: Emitting Events (The Producer)

Producers append events to the stream using XADD. The * tells Redis to auto-generate a unique timestamp-based event ID:

# Producer writes an OrderPlaced event:
XADD stream:orders * order_id "ord_9942" user_id "usr_102" amount "149.50" status "created"

Step 2: Creating a Consumer Group

Before workers can read as a group, create the consumer group using XGROUP CREATE. The $ parameter tells Redis to only deliver new messages arriving from this point forward:

# Create group 'payment_workers' on stream 'stream:orders'
XGROUP CREATE stream:orders payment_workers $ MKSTREAM

Step 3: Worker Consumer Implementation in PHP / Node.js

Here is a complete, resilient background worker that reads incoming events, processes the business logic, and sends an atomic acknowledgment (XACK):

connect('127.0.0.1', 6379);

$stream = 'stream:orders';
$group = 'payment_workers';
$consumer = 'worker_' . getmypid();

echo "Worker [{$consumer}] listening for events on {$stream}...
";

while (true) {
    // Read new pending messages for this consumer group (BLOCK for 2000ms if empty)
    $messages = $redis->xReadGroup($group, $consumer, [$stream => '>'], 10, 2000);

    if (empty($messages) || !isset($messages[$stream])) {
        continue; // Keep polling gracefully
    }

    foreach ($messages[$stream] as $messageId => $fields) {
        echo "Processing Event ID: {$messageId}
";

        try {
            // 1. Enforce Idempotency check before processing
            if (isEventAlreadyProcessed($redis, $messageId)) {
                echo "Duplicate event detected ({$messageId}). Skipping.
";
                $redis->xAck($stream, $group, [$messageId]);
                continue;
            }

            // 2. Execute Business Logic (e.g., process credit card charge)
            processOrderPayment($fields['order_id'], $fields['amount']);

            // 3. Mark Event as Processed in Idempotency Store (TTL: 7 days)
            markEventProcessed($redis, $messageId);

            // 4. Acknowledge message delivery to remove from Pending Entries List (PEL)
            $redis->xAck($stream, $group, [$messageId]);
            echo "Successfully processed & ACKed Event ID: {$messageId}
";

        } catch (Throwable $e) {
            echo "Error processing event {$messageId}: " . $e->getMessage() . "
";
            // Do NOT acknowledge. Leave in PEL for retry or Dead Letter Queue shunting.
        }
    }
}

function isEventAlreadyProcessed(Redis $redis, string $eventId): bool {
    return (bool) $redis->exists("idempotency:event:{$eventId}");
}

function markEventProcessed(Redis $redis, string $eventId): void {
    $redis->setex("idempotency:event:{$eventId}", 604800, "1");
}

function processOrderPayment(string $orderId, string $amount): void {
    // Payment execution logic here...
}

Guaranteeing Idempotency: The #1 Distributed System Requirement

In distributed networks, network timeouts, TCP resets, and producer retries mean that duplicate messages are guaranteed to occur. Most event systems provide At-Least-Once Delivery guarantees, meaning an event might arrive more than once.

If your consumer is not idempotent, a duplicate OrderPlaced event will charge the customer’s credit card twice or double-ship inventory! An operation is idempotent if executing it multiple times produces the exact same outcome as executing it once.

The Idempotency Key Pattern:

  1. The producer assigns a unique cryptographic or UUID identifier to the event (e.g. event_id: evt_01h8x9p3q or hash(order_id + user_id + timestamp)).
  2. When a consumer receives an event, it executes an atomic lock in Redis or an insert into an idempotency_keys database table:
    INSERT INTO processed_events (event_id, processed_at) VALUES ('evt_01h8x9p3q', NOW());
  3. If the insert succeeds, the consumer executes the payment and commits. If a unique key violation occurs, the consumer knows the event was already handled, immediately sends an XACK, and safely exits.

Handling Poison Pills with Dead Letter Queues (DLQ)

A Poison Pill is an event that cannot be processed due to corrupt data, unparseable JSON, or unexpected edge cases (e.g. negative prices). When a consumer tries to process a poison pill, it throws an unhandled exception and crashes. When the worker restarts, it reads the exact same event and crashes again—locking up the entire consumer group in an infinite failure loop!

The Dead Letter Queue Pattern:

  • Track the delivery count of each event in the Pending Entries List (PEL) using XPENDING.
  • If an event fails more than 3 to 5 times, a supervisor process claims the message with XCLAIM, forwards the payload to a dedicated stream:orders:dead_letter stream, and executes an XACK on the main stream.
  • The main pipeline continues running smoothly without blocking other customers. DevOps teams receive an automated alert in Slack or PagerDuty to inspect and debug the poison event in the DLQ.

Integrating Webhooks into Event-Driven Systems

In modern SaaS platforms, external developers often want to know when events occur in your system (e.g., Stripe notifying your app when a subscription renews, or GitHub notifying your CI/CD pipeline when a commit is pushed). Webhooks are essentially HTTP-based Event Streams dispatched to third-party endpoints.

Never dispatch external webhook HTTP calls synchronously within your core API! Instead:

  1. Your API writes internal event to the event stream: XADD stream:webhooks * user_id 101 event "invoice.paid" payload "{...}".
  2. Dedicated webhook delivery worker pools read from the stream.
  3. Workers sign the payload using HMAC SHA-256 (X-Signature-SHA256) with the customer’s shared secret so the client can verify authenticity.
  4. If the client’s server is down, the worker records the failure and schedules exponential retries (e.g. at 5m, 30m, 2h, 24h) without affecting internal systems.

Event-Driven Architecture Readiness Checklist

Before launching an event-driven microservice system into production, ensure you have satisfied these essential criteria:

  • ✔ Engine Selection: Use Redis Streams for ultra-low latency internal microservice jobs; use Apache Kafka for multi-terabyte analytical logging and long-term event retention.
  • ✔ Idempotency Enforcement: Every consumer validates unique event IDs before altering state.
  • ✔ Dead Letter Queues Active: Max retry limits configured to isolate poison pills and prevent worker crash loops.
  • ✔ Consumer Lag Monitoring: Telemetry alerts triggered if consumer lag (unprocessed event queue depth) exceeds safe thresholds.
  • ✔ Schema Evolution: Event payloads use backward-compatible JSON or Protobuf schemas so new field additions do not break existing consumers.

By adopting Event-Driven Architecture, your engineering teams can build modular, fault-tolerant backends that scale effortlessly to handle millions of transactions without downtime or performance degradation.

Found this guide helpful? Share with your peers

Help fellow engineers, students, and professionals discover this resource.

1-Click Viral Share

Leave a Comment

Your email address will not be published. Required fields are marked *