All projects

Distributed Systems / Streaming

Real-Time Commerce Platform

An event-driven commerce backend that processes every event at least once and applies it exactly once. A Go processor validates each Kafka event, guards it with an idempotency lease and writes it in one PostgreSQL transaction with its fraud decision and outbox row before committing the offset.

3 workers, 3 partitions1,400 evt/s
Sustained by the Go processorHeld in 2 of 2 repeats on the same benchmark where the Python processor fell behind in both. Every repeat processed exactly the events it injected.
89 ms against 1,686 ms at 1,400 evt/s19×
Lower p95 than PythonEnd-to-end p95 at the same request rate, with 30–35% less processor CPU. Medians of two repeats, measured locally in Docker.
6 workers, about 25% more~2,800 evt/s
Saturated, one transaction per batchMean of each run's best rate, against about 2,220 evt/s with one transaction per event. PostgreSQL commits fell from 900–1,700 a second to 40–55.

Kafka can deliver twice. A payment cannot apply twice.

A consumer that commits its offset after processing will sometimes see the same record again: after a rebalance, a crash or a slow commit. If processing that record again creates a second order, a second charge or a second fraud alert, the system is wrong, not just noisy.

Real-Time Commerce Platform accepts at-least-once delivery and makes every effect apply once. Each event is validated, guarded by an idempotency lease and written in one PostgreSQL transaction together with its fraud decision and outbox row. Only then is its offset committed.

Anything that cannot be applied lands in a dead-letter queue, where an operator can triage it and replay it. The whole stack starts with one make demo-up.

A commerce backend you can watch work.

Start a scenario from the console, then follow its events through the processor, the fraud engine and the dead-letter loop.

Generate realistic journeys

Seeded personas, from normal shoppers to bots, account takeovers and discount hunters, produce versioned events in a valid order: sessions, carts, orders, payments and refunds. Eight fixed scenarios bound the count and rate.

Every run is repeatable from its seed, so a result can be checked again.

Apply each event once

Delivery is at least once. A Redis lease stops two workers from processing the same event at the same time, and PostgreSQL uniqueness rejects a second durable effect.

A redelivered payment is recognised and skipped instead of charging an order twice.

Commit atomically

Business state, the fraud decision and the outbox row for one event commit in one transaction. The Kafka offset moves only after that, in bounded batches that never skip an unresolved record.

A crash at any point leaves either everything or nothing, and the event comes back.

Score fraud as it streams

Deterministic rules, among them payment velocity, failed-payment bursts, new devices, country mismatch and refund abuse, produce APPROVE, REVIEW or BLOCK with an explainable score. Alerts leave through a transactional outbox.

Every alert names the rules it matched and is published only if its decision committed.

Keep failures recoverable

Transient failures retry with capped, jittered backoff. Invalid or exhausted records go to a dead-letter topic, a sink copies them into PostgreSQL, and the console triages, discards or replays them.

Replay is offered only for failures where a second try can succeed.

One event through the processor.

The Overview during a mixed-traffic run, refreshing every 5 seconds. Every number comes from Prometheus or PostgreSQL. Below it, what the Go processor does with each record.

The console's Overview during a mixed-traffic run: throughput, p95 latency, consumer lag, fraud alerts, dead letters and outbox backlog updating live
  1. Validate. One shared envelope and payload registry checks the record. An invalid contract goes straight to the dead-letter topic.
  2. Lease. A token-checked Redis lease reserves the event. If it is already completed the record is a duplicate and is skipped; if another worker holds it, the record stays unresolved and its offset is not committed.
  3. Write once. Business state, the fraud decision, the processed_events row and the outbox row commit in one PostgreSQL transaction, together with the other new events of the same fetched batch.
  4. Retry or dead-letter. A transient error retries with capped, jittered backoff. A permanent error, or retries running out, releases the lease and publishes the record to the dead-letter topic, confirmed before going further.
  5. Mark complete. After the commit Redis records the event as completed, so a redelivery is recognised quickly. If Redis forgets, PostgreSQL uniqueness still refuses a second effect.
  6. Commit the offset. Offsets are committed per partition in contiguous batches of 50 records or 100 ms, flushed on idle, rebalance and shutdown, and never past an unresolved record.

What the offset promises.

The offset is a delivery cursor, not proof that something happened once. These guarantees come from the order of the steps above.

GuaranteeHow
No lost eventsOffsets are committed only after terminal handling: applied, recognised as a duplicate, or confirmed in the dead-letter topic.
No double effectsA Redis token-checked lease coordinates active work, and PostgreSQL uniqueness on processed_events and business keys protects durable effects even if Redis forgets.
Alerts follow decisionsFraud alerts and outbox rows commit with the decision. A separate publisher claims committed rows and publishes at least once.
OrderingPer partition, with events keyed by customer. There is no global order.

The processor never calls another service.

Everything it produces is either a row in its transaction or a Kafka record. PostgreSQL is the system of record, and Redis holds only coordination state that can be rebuilt. Docker Compose runs it all on one local network with a single KRaft broker.

Scenarios started from the console publish commerce events to Kafka for at-least-once processing. The Go processor takes a Redis lease, commits business state, fraud decisions and outbox rows in one PostgreSQL transaction per fetched batch, and publishes invalid or exhausted records to a dead-letter topic. A sink copies dead letters into PostgreSQL for triage and replay, and a separate publisher emits fraud alerts. Prometheus and Grafana observe the platform without changing processing outcomes.

Scenario to durable processing

The interactive demo reaches the same Kafka and processor path used by generated commerce events.

Browser controls Console. Console then connects to Control API. Control API starts scenario Scenario Runner. Scenario Runner publishes commerce.events. commerce.events at least once Event Processor.

  1. ClientBrowserbounded scenarios
  2. ClientConsoleNext.js
  3. ServiceControl APIFastAPI
  1. ServiceScenario Runnershared event generator
  2. Messagingcommerce.eventspartitioned Kafka topic
  3. ServiceEvent ProcessorGo, partition-scoped handling

Processor state boundaries

Operational coordination stays reconstructible; durable identity and business effects share one database boundary.

Event Processor coordinates Redis. Event Processor commits durable effects PostgreSQL.

  1. ServiceEvent Processorterminal handling
  2. PersistenceRedisleases, completion markers
    PersistencePostgreSQLdurable system of record
    • business + fraud state
    • processed identity + outbox

Confirmed failure path

The processor only publishes failures to Kafka; a separate sink makes them queryable, so a database outage cannot block the failure path.

Event Processor publishes invalid / exhausted commerce.events.dlq. commerce.events.dlq copied by DLQ sink. DLQ sink triage, replay dead_letters.

  1. ServiceEvent Processorclassifies terminal failure
  2. Messagingcommerce.events.dlqconfirmed before the offset moves
  1. ServiceDLQ sinkidempotent on topic, partition, offset
  2. Persistencedead_lettersreplayable records go back to commerce.events

Derived fraud alerts

Committed outbox rows publish independently from the source-event transaction.

PostgreSQL outbox claims Fraud Outbox Publisher. Fraud Outbox Publisher publishes commerce.fraud-alerts.

  1. PersistencePostgreSQL outboxcommitted with source effects
  2. ServiceFraud Outbox Publisherindependent delivery loop
  3. Messagingcommerce.fraud-alertsKafka topic

Non-critical observability

Application metrics and infrastructure exporters are scraped without changing processing outcomes.

Services + exporters scraped by Prometheus. Prometheus visualized in Grafana.

  1. ObservabilityServices + exportersbounded-label metrics
  2. ObservabilityPrometheusplatform signals
  3. ObservabilityGrafanaprovisioned dashboards

Architecture notes

  • The Event Processor—not the main Kafka topic—publishes invalid or exhausted records to commerce.events.dlq.
  • PostgreSQL is the durable system of record; Redis contains reconstructible coordination state.
  • Accepted event effects, fraud decisions, processed identity and outbox rows commit in one PostgreSQL transaction.
  • Kafka offsets commit in bounded per-partition batches (50 records or 100 ms), flushed on idle, rebalance and shutdown, and never past an unresolved record; delivery is at least once and ordering is partition scoped.
  • The new events of each fetched batch, up to 50, commit in one PostgreSQL transaction; a failed batch is retried one event at a time.
Read the architecture

Failures stay recoverable.

A dead letter moves from NEW to TRIAGED, DISCARDED or REPLAYED, and can be reopened. These rules keep that loop from losing or duplicating anything.

A dead letter is confirmed before the offset moves

The processor publishes a failed record and waits for Kafka to confirm it before committing the source offset, so a crash in between redelivers the event instead of losing it.

Read the design

A database outage cannot block the failure path

The processor only publishes failures to Kafka. A separate sink, idempotent on topic, partition and offset, copies them into PostgreSQL.

Read the design

Replay changes status only after delivery

A replay re-publishes the original key, value and headers to the source topic. The row stays locked while it sends, and its status changes only after Kafka confirms delivery.

Read the design

Alerts never outrun their decision

The outbox row commits in the same transaction as the fraud alert it carries. If the publisher crashes mid-send, the row is still pending and is published on the next pass.

Read the design

Make duplicates harmless instead of impossible.

Two layers of idempotency

Redis alone is fast but reconstructible: a restart or an expired lease can forget an event. PostgreSQL alone pays a database round trip for every record. Redis answers the common case and coordinates workers; the processed_events ledger is the authority when Redis cannot answer.

At least once, applied once

Exactly-once across Kafka and PostgreSQL would need a second coordination protocol. Instead the consumer is idempotent: duplicates are expected, and every write path is built to tolerate them.

Port the processor when the numbers say so

The Go processor replaced the Python one only after an A/B on the unchanged benchmark, from the same reset state. Go held 1,400 evt/s where Python fell behind, at about 19 times lower p95 latency and 30–35% less CPU.

One transaction per batch

Every event used to pay for its own COMMIT. Committing the new events of each fetched batch together cut PostgreSQL commits from about 900–1,700 a second to 40–55. A failed batch is retried one event at a time, so one bad event never takes the others down.

Replay only what can succeed

Only retry-exhausted and missing-dependency records are marked replayable. The others fail the same way every time, so the console offers triage and bulk discard instead of a button that cannot work.

Read the design decisions

Measured, not guessed.

The processor was ported from Python to Go and measured with the unchanged benchmark against both, from the same reset state: 3 workers, 3 partitions, 2 repeats per rate, 45 s of measured load. A repeat counts as sustainable when lag grows by at most 5 events a second.

RequestedRuntimeServed, evt/sEnd-to-end p95Sustainable
1,200 evt/sPython1,197235 ms2 of 2
1,200 evt/sGo1,19751 ms2 of 2
1,400 evt/sPython1,3711,686 ms0 of 2
1,400 evt/sGo1,39589 ms2 of 2
1,700 evt/sPython1,47712,939 ms0 of 2
1,700 evt/sGo1,6761,065 ms0 of 2

Medians of two repeats. Every repeat in both runtimes processed exactly the events it injected, with zero errors. Peak processor CPU was 30–35% lower on Go at the same rate.

Then the processor stopped paying for one COMMIT per event. It now commits the new events of each fetched batch, up to 50, in one transaction. Measured with 6 workers, runs interleaved because each run grows the database by about 1.8 GB:

TransactionsHighest service rateMean of each run's best
One transaction per event2,572 evt/s~2,220 evt/s
One per batch (default)3,018 evt/s~2,800 evt/s

Every rate in this sweep was above the sustainable boundary, so these are saturated throughputs. The Docker VM's 8 CPUs are full here, so the next gain needs CPU, not code. Local measurements, not production SLAs.

Read the performance report

The working console.

Every screen below is the running stack. Open any screenshot to see it full size.

Overview: throughput, p95 latency, consumer lag, fraud alerts, dead letters and outbox backlog; the event pipeline from generator to outbox publisher; service-level gauges.
See the whole pipeline

Six KPIs with short trends, the pipeline stage by stage and service levels against their alert limits. Ten open tabs cost Prometheus no more than one.

Scenarios page: the catalog with Mixed traffic selected, its persona distribution, event count, rate and seed, and the Start scenario button.
Start a scenario

Eight fixed scenarios, each with a stated purpose. Count, rate, seed and anomalies are bounded on the server, and mixed traffic takes a persona distribution.

A mixed-traffic run in progress: the generated percentage climbing, processed events keeping pace, dead letters, and approve, review and block counts growing.
Watch a run live

Progress streams over Server-Sent Events: generated and processed counts, dead letters and fraud decisions as they are made.

Runs page: run history with scenario, status, events, decisions and start time.
Keep every run

Each run's exact outcome is read from PostgreSQL rather than Prometheus, so its numbers never drift with a scrape interval.

Fraud page: 20,165 decisions split into approve, review and block, alerts by severity, and the latest alerts with matched rules and publication state.
Read every fraud decision

Decisions across runs, alerts by severity, and each alert's score, decision, matched rules and whether the outbox has published it.

Dead letters page: records waiting for a look, counts by status, failure categories with Replayable badges and bulk actions, and the most recent records.
Triage dead letters

Every record the processor could not apply, grouped by status and failure category. Replayable categories are marked; the rest can be triaged or discarded in bulk.

A dead letter's drawer: a replayed record whose replay failed again, with a link to the new record, the reason, source partition and offset, the payload, headers and triage actions.
Follow a replay

The original payload and headers, why it failed and where it came from. If a replay dead-letters again, the drawer links the new record.

Infrastructure page with the alerts popover open: DLQ sink is down, a critical alert, and the DLQ Sink row marked Down.
See an alert fire

The DLQ sink was stopped on purpose, and DLQSinkDown fired a minute later. Critical alerts stay in the bell until they resolve.

Grafana Commerce Platform Overview: health, consumer lag, received and processed rates, processing latency, DLQ and duplicate rate, fraud decisions, alerts and pending outbox rows.
Watch it in Grafana

Commerce Platform Overview, one of seven provisioned dashboards: lag, rates, processing p50/p95/p99, dead letters, duplicates, fraud and outbox.

Tested against real services.

CI runs four jobs on every push. The integration job starts Kafka, PostgreSQL and Redis and runs the tests against the Go processor container, failing if a marked test skips.

Go against Python

1,400 evt/s sustained

Same benchmark, same reset state

3 workers, 3 partitions, 2 repeats per rate. Go held 1,400 evt/s in 2 of 2 repeats at 89 ms p95; Python held it in 0 of 2 at 1,686 ms. Every repeat in both runtimes processed exactly the events it injected, with zero errors.

One transaction per batch

~2,800 evt/s

6 workers, saturated, about 25% more

Mean of each run's best rate, against about 2,220 evt/s with one transaction per event; the single highest rate was 3,018 evt/s. Runs were interleaved because each grows the database by about 1.8 GB. The Docker VM's 8 CPUs were full.

Earlier, on the Python processor

750 → 1,050 evt/s

Sustainable, isolated pipeline, +40%

Batched offset commits (about 28.6 times fewer commit calls) moved the boundary from about 750 to 900 evt/s; query-plan-driven indexes, such as the recent-payment lookup going from 10.897 to 0.253 ms, then moved it to about 1,050 evt/s.

Integration tests

Real Kafka, PostgreSQL, Redis

Against the Go processor container

A duplicate delivery is applied once, with one durable effect, Redis completion recorded and the offset advanced. A deterministic failure reaches the real dead-letter topic after retries, with the offset committed only after delivery. The job fails if a marked test skips.

Process crashes, a crash between the PostgreSQL commit and Redis completion, and rebalance recovery are designed for but not yet executed in CI.

Run it locally.

  • Go
  • Python
  • TypeScript
  • FastAPI
  • Next.js
  • Kafka
  • PostgreSQL
  • Redis
  • Prometheus
  • Grafana
  • Docker Compose

One command builds and starts Kafka, PostgreSQL, Redis, the processor, the dead-letter sink, the outbox publisher, Prometheus, Grafana, the exporters, Kafka UI and the console. No configuration is needed.

git clone https://github.com/negativexq/real-time-commerce-platform.git
cd real-time-commerce-platform
make demo-up
make demo-run-mixed
# Open http://localhost:3003

Kafka runs as one broker without replication, which suits local development, not durability testing. The README lists what changes for production.

In short

What is Real-Time Commerce Platform?
Real-Time Commerce Platform streams customer journeys, from browsing through payment and refund, through Kafka into a Go processor. Redis leases and PostgreSQL uniqueness make each event apply once, business state, fraud decision and outbox row commit in one transaction, and records that cannot be applied go to a dead-letter queue the console can triage and replay. Prometheus, Grafana and a Next.js console show every stage.
What problem does Real-Time Commerce Platform solve?
Kafka delivers at least once, so a consumer will sometimes see the same payment twice. The project makes that harmless instead of pretending it cannot happen, keeps every failure recoverable, and treats throughput as something to measure: the processor moved from Python to Go only after an A/B on the same benchmark showed it held 1,400 evt/s where Python fell behind.

Follow the implementation.