Markdown Editor

Streaming Solution Design Template (Kafka, Flink, AsyncAPI)

Latency SLOs, delivery guarantees, CDC sources, AsyncAPI 3.1.0 contracts, topics, watermarks, windows, state, exactly-once, capacity, lag

ArchitectureCompletAsyncAPI 3.1.0; CloudEvents 1.0.2; Apache Kafka 4.x and Apache Flink 2.x conceptsstreamingsolutiondesign

Mode d'emploi: Use it when you build a real-time solution on an existing streaming platform and stream processor, such as live stock or fraud alerts. Fill the latency objectives and the delivery guarantee per output first, then topic keys, partitions and state sizing. The main pitfall is demanding exactly-once everywhere without noticing that transactional sinks delay results until each checkpoint completes.

Aperçu

Streaming Solution Design: [Solution name]

Solution design for a real-time data solution built on an event streaming platform and a stream processor (for example Apache Kafka and Apache Flink): use cases and latency objectives, sources and change data capture, event contracts and schema governance, topic design, the processing topology, time, windows and state, delivery guarantees (exactly-once and idempotency), sinks, capacity, scaling, reliability, security, lag monitoring and testing. Event contracts are documented with the AsyncAPI Specification 3.1.0. Replace every [bracketed] value and every row marked Example. Worked examples follow a retailer that turns store and online sales events into live stock availability and payment fraud alerts.

Document control

FieldValue
Document ID[STR-001]
Solution name[Name]
Streaming platform[Apache Kafka 4.x managed service / self-managed cluster / other], version [x.y]
Stream processor[Apache Flink 2.x / Kafka Streams / other], version [x.y]
Schema registry[Product and version]
Version[0.1]
Status[Draft / In review / Approved / Superseded]
Owner[@streaming-architect]
Approvers/reviewers[@platform-owner], [@security-architect], [@data-platform-architect], [@sre-lead]
Last updatedYYYY-MM-DD
Classification[Internal / Confidential]

Approvals

RoleNameDecisionDate
Business owner[@name][Approve / Approve with conditions / Reject]YYYY-MM-DD
Streaming platform owner[@name][Decision]YYYY-MM-DD
Security[@name][Decision]YYYY-MM-DD
SRE[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft
1.0YYYY-MM-DD[@name]Example: Stock availability stream approved
1.1YYYY-MM-DD[@name]Example: Added fraud scoring job and alert sink

Contents

1. Use cases and latency objectives

IDUse caseConsumerLatency objective (p95)Value of lower latencyBatch alternative rejected because
SUC-001 (Example)Live stock availability per product and storeWeb shop, store app30 secondsFewer orders for out-of-stock itemsHourly batch caused 2 % order cancellations
SUC-002 (Example)Card-not-present fraud alertPayment risk team, order service2 secondsOrder held before shipmentFraud detected after dispatch
SUC-003 (Example)Sales events to the lakehouse bronze layerData platform5 minutesIntraday reportingHourly extracts load the POS database
[SUC-NNN][Use case][Consumer][Latency][Value][Reason]

Record the objectives in the SLO document (dev/slo-doc) with the measurement point at each end.

2. Requirements and delivery guarantees

2.1 Requirements

IDRequirementTypeAcceptance criterion
SRQ-001 (Example)Compute available stock as on-hand minus reserved, per product and storeFunctionalMatches the stock system snapshot within 0.5 % at daily reconciliation
SRQ-002 (Example)Score each online payment with rules and a modelFunctionalScore attached to 100 % of payment events
SRQ-003 (Example)Handle peak of 50,000 events per secondPerformanceLoad test at 1.5 times peak without lag growth
SRQ-004 (Example)No lost sales event after a broker or job failureReliabilityChaos test with zero missing events against source counts
SRQ-005 (Example)Personal data encrypted in transit and access-controlled per topicSecurityAudit of ACLs and TLS configuration
[SRQ-NNN][Requirement][Type][Criterion]

2.2 Delivery guarantee per output

OutputGuaranteeHow it is achievedReason
stock.availability topic (Example)Effectively-onceTransactional sink committed on checkpoint; consumers read committed onlyDownstream sums would drift with duplicates
Fraud alert to order service (Example)At-least-once with idempotent receiverAlert carries a deterministic identifier; receiver ignores repeats2-second objective rules out waiting for checkpoints
Bronze tables (Example)Effectively-onceSink commits files and table snapshot on checkpointReplays must not duplicate rows
[Output][Guarantee][Mechanism][Reason]

3. Sources and change data capture

IDSourceMethodEvent typesKeyRate (peak)Owner
ESR-001 (Example)POS gatewayNative producer, idempotentSaleRecorded, ReturnRecordedstore_id30,000 per second@retail-ops
ESR-002 (Example)E-commerce order serviceTransactional outbox read by CDCOrderPlaced, OrderCancelled, PaymentAuthorisedorder_id8,000 per second@ecom-lead
ESR-003 (Example)Warehouse systemLog-based CDCStockAdjusted, StockReservedproduct_id plus location_id12,000 per second@supply-chain
[ESR-NNN][Source][Method][Types][Key][Rate][@owner]

Example peak total: 30,000 + 8,000 + 12,000 = 50,000 events per second. Section 10 sizes the platform from this figure. Snapshot, ordering and schema change handling for CDC follow CDC Pipeline Design (system-design/design-cdc-pipeline).

4. Event contracts and schema governance

4.1 Contract rules

  1. Describe each channel and message in an AsyncAPI 3.1.0 document (asyncapi: 3.1.0, with info, servers, channels, operations and components), stored with the producer's code and published to the catalogue. Detail it in Event API Specification (architecture/event-api-specification).
  2. Register payload schemas (Avro, Protobuf or JSON Schema) in the schema registry; producers fail fast if the schema is not registered.
  3. Use the envelope attributes of CloudEvents 1.0.2 (id, source, type, specversion, time) where events cross organisational boundaries, so routing does not depend on the payload.
  4. Include an event identifier, the business event time and the producer version in every event.
  5. Treat the topic, key, schema and guarantee of a published stream as a data contract (ai-data/data-contract).

4.2 Compatibility policy

Stream classCompatibility mode (Example)Allowed changeBreaking change process
Internal to one teamBackwardAdd fields with defaults, delete fieldsNew topic version, dual publish for [2] weeks
Shared across domainsFull transitiveAdd optional fields with defaults onlyNew major contract version, consumer sign-off, [90] days dual publish
External partnersFull transitive plus AsyncAPI reviewAs abovePartner notice of [6] months

Compatibility mode names follow common schema registry practice (backward, forward, full, each optionally transitive, or none); check the modes your registry supports.

5. Topic design

TopicKeyPartitionsRetentionCleanupReplicationProducersConsumers
retail.sales.v1 (Example)store_id247 daysDelete3, min in-sync 2POS gatewayStock job, bronze sink
ecom.orders.v1 (Example)order_id127 daysDelete3, min in-sync 2Outbox CDCFraud job, stock job, bronze sink
wms.stock-changes.v1 (Example)product_id:location_id247 daysDelete3, min in-sync 2WMS CDCStock job, bronze sink
stock.availability.v1 (Example)product_id:store_id24Latest value per keyCompact3, min in-sync 2Stock jobWeb shop, store app
fraud.alerts.v1 (Example)order_id630 daysDelete3, min in-sync 2Fraud jobOrder service, risk team
[domain.entity.vN][Key][Count][Retention][Policy][RF][Producers][Consumers]

Naming convention: <domain>.<entity-or-event>.<major version>. Where an Event-Driven Architecture Design (architecture/event-driven-architecture-design) exists, its convention (section 5.1, with environment and kind parts) takes precedence; the short names here keep the examples readable. Keep a dead-letter topic per consuming job (<source-topic>.dlq.<job>, the same rule as the EDA design) with the original payload, the error and the source offset.

Example skew check: store_id has 1,800 values over 24 partitions, about 75 stores per partition. The largest store produces [3] times the average volume, so verify the hottest partition stays under the per-partition limit measured in section 10.

6. Processing topology

JobOperators with stateParallelism (Example)DeploymentOwner
stock-availability (Example)Availability per product and store, deduplication by event id24Application mode on Kubernetes, one job per use case@retail-data
fraud-scoring (Example)Per-customer windows, model in memory12Application mode, separate cluster@risk-data
[Job][Stateful operators][Parallelism][Deployment][@owner]

7. Time, windows and state

7.1 Time and lateness

StreamTime usedWatermark strategyAllowed latenessLate events after lateness
retail.sales.v1 (Example)Event time (till timestamp)Bounded out-of-orderness of 30 seconds; idle source detection after 1 minute10 minutesSide output to a correction topic, applied in the lakehouse
ecom.orders.v1 (Example)Event timeBounded out-of-orderness of 5 seconds1 minuteScored without window features, flagged
[Stream][Time][Strategy][Lateness][Handling]

A watermark at time t asserts that no further events at or before t are expected. Watermarks advance per parallel source instance, and an operator with several inputs follows the slowest; an idle partition can therefore stall results, which is why idle source detection matters.

7.2 Windows

IDWindowTypeSizeTriggerUse
WIN-001 (Example)Customer payment featuresSliding10 minutes, every 1 minuteOn watermarkFraud score
WIN-002 (Example)Store sales per minuteTumbling1 minuteOn watermark plus early firing every 10 secondsStore dashboard
WIN-003 (Example)Browsing sessionSessionGap of 30 minutesOn gapBasket abandonment
[WIN-NNN][Window][Type][Size][Trigger][Use]

7.3 State

OperatorState contentKeysSize per keyTotal stateTime-to-liveBackend
Availability (Example)On-hand, reserved, last event id2,000,000 product-store pairs2 KB4 GBNone (live entities)Embedded key-value store on local disk, incremental checkpoints
Deduplication (Example)Event ids seenEvents in last 15 minutes64 bytesSection 10.415 minutesAs above
Customer windows (Example)Payment amounts and countsActive customers1 KB[Size]24 hoursAs above
[Operator][Content][Keys][Size][Total][TTL][Backend]

Set a time-to-live on every state that is not a live entity; state that grows without bound is the most common cause of slow checkpoints and long recovery.

8. Exactly-once and idempotency

LayerMechanism (Example)Configuration to check
ProducersIdempotent producer with acknowledgement from all in-sync replicasacks set to all, idempotence enabled, retries enabled
Processor stateConsistent checkpoints of all operator state and source offsetsCheckpoint interval [60 s], minimum pause, timeout, retained checkpoints
Broker sinkTransactional writes committed when a checkpoint completesUnique transactional id prefix per job; transaction timeout longer than the longest checkpoint plus restart time
Downstream consumersRead committed data onlyConsumer isolation level read committed
External database sinkIdempotent upsert keyed by business key plus event versionUpsert ignores versions older than stored
AlertsDeterministic alert id derived from order id and rule idReceiver stores processed ids for [7] days

Consequence of the transactional sink: results become visible to read-committed consumers only after the checkpoint completes. With a 60-second interval the stock topic can lag by up to about a minute plus commit time, which breaks the 30-second objective in SUC-001. Example choice: checkpoint the stock job every 10 seconds (state is about 6.9 GB, section 10.4, and checkpoints are incremental) and keep the fraud alert path out of the transaction, as stated in section 2.2. Record the decision in the Architecture Decision Log (architecture/architecture-decision-log).

9. Sinks and serving

IDSinkDataWrite patternGuaranteeConsumer
SNK-001 (Example)Compacted topic stock.availability.v1Latest availability per keyUpsert by keyEffectively-onceWeb shop cache, store app
SNK-002 (Example)Key-value cacheAvailability for page renderingUpsert from SNK-001 by a consumer serviceAt-least-once, idempotentWeb shop
SNK-003 (Example)Lakehouse bronze tableAll sales, order and stock eventsAppend, commit on checkpoint, compaction dailyEffectively-onceData platform
SNK-004 (Example)fraud.alerts.v1 and order service APIAlertsPublish then call with retriesAt-least-once, idempotentOrder service
[SNK-NNN][Sink][Data][Pattern][Guarantee][Consumer]

Streaming sinks into the lakehouse produce many small files; schedule compaction as described in Data Platform Architecture (architecture/data-platform-architecture).

10. Capacity estimation

Units in this section are decimal: 1 KB = 1,000 bytes, 1 MB = 10^6 bytes, 1 TB = 10^12 bytes. All figures are Example values.

10.1 Throughput

StepCalculationResult
Peak ingress50,000 events per second x 1 KB average50 MB/s
Replicated write at replication factor 350 MB/s x 3150 MB/s across brokers
Consumer egress (sales read by two groups, orders by three, stock changes by two; section 5)30 MB/s x 2 + 8 MB/s x 3 + 12 MB/s x 2108 MB/s

Consequence: brokers must sustain 150 MB/s of disk writes plus 100 MB/s of replication traffic between brokers (two follower copies of 50 MB/s) and about 108 MB/s of consumer reads, mostly served from page cache; size network and disks with [50 %] headroom.

10.2 Retention storage

StepCalculationResult
Average daily volume20,000 events per second x 1 KB x 86,400 s1.728 TB per day
Seven days logical1.728 TB x 712.096 TB
With replication factor 312.096 TB x 336.288 TB

Consequence: about 36 TB of broker storage for 7 days. If the platform offers tiered storage, keep [1] day on local disk and the rest in object storage, which cuts local disk to about 1.728 x 3 = 5.2 TB.

10.3 Partitions

StepCalculationResult
Per-partition throughput measured in a load testGiven5 MB/s
Peak on retail.sales.v1 (POS stream only, ESR-001)30,000 events per second x 1 KB30 MB/s
Minimum partitions for peak30 MB/s / 5 MB/s6
Minimum partitions for twice today's peak60 MB/s / 5 MB/s12
Chosen for retail.sales.v1Three-year growth and stock job parallelism; divides evenly by 8, 12 and 2424

Consequence: 24 partitions cap the parallelism of any consumer group at 24. Increasing partitions later changes key-to-partition mapping and breaks per-key ordering for in-flight data, so choose the count for the three-year growth now.

10.4 State

StepCalculationResult
Availability state2,000,000 keys x 2 KB4 GB
State per subtask at parallelism 244 GB / 24about 167 MB
Deduplication state50,000 events per second x 900 s x 64 bytes2.88 GB
Total stock job state4 GB + 2.88 GBabout 6.9 GB

Consequence: about 290 MB of state per subtask (6.9 GB / 24) restores in seconds from local disk and in under a minute from object storage at typical throughput; 10-second incremental checkpoints are feasible. If deduplication by event id were held for 24 hours instead of 15 minutes, it would grow 96 times to about 276 GB, so keep the window short and rely on idempotent producers for older duplicates.

11. Scaling and performance

ComponentScaling methodLimitTrigger (Example)
BrokersAdd brokers and reassign partitionsDisk and network per brokerDisk above 70 % or network above 60 %
Stream jobsRescale parallelism from a savepoint, or autoscalerPartition count of the input topicConsumer lag growing for 5 minutes
SinksScale the receiving store; batch writesWrite capacity of the storeBackpressure on sink operator above 50 %
Schema registryReplicas behind a load balancerRarely the bottleneckRequest latency above 50 ms

Performance targets: p95 end-to-end latency per SUC objective, measured by comparing event time with sink write time on sampled events. Plan load tests in the Performance Test Plan (quality/performance-test-plan).

12. Reliability and recovery

Failure (Example)EffectDetectionRecovery
One broker failsLeaders move to other replicas; producers retryUnder-replicated partitions alertAutomatic; replace broker
Job task manager failsJob restarts from last checkpoint; output replays to last commitRestart counter, lagAutomatic within [60 s]
Poison messageParsing failsDead-letter topic rateMessage routed to DLQ, job continues
Downstream cache unavailableConsumer service lagsLag on its consumer groupRetry with backoff, cache rebuilt from compacted topic
Region outagePlatform unavailable in the regionHealth checksFail over to the standby region per resilience tier

Recovery objectives: RPO [1 minute] and RTO [30 minutes] for the stock stream (tier per Resilience Tiering and HA/DR Design, architecture/resilience-tiering-ha-dr-design). Cross-region replication copies topics asynchronously; consumer offsets must be translated, and stateful jobs restart from the latest replicated savepoint or rebuild state by replaying compacted topics. Take a savepoint before every job upgrade and test restore quarterly.

13. Security and privacy

ControlDesign (Example)
AuthenticationMutual TLS or OAuth-based authentication for every client; one identity per producer and job
AuthorisationACLs per topic and consumer group; producers write only their topics
EncryptionTLS in transit; encryption at rest on brokers and tiered storage
Personal dataNo personal data in keys; customer identifiers pseudonymised in sales events; card data never on the stream (tokens only)
Retention and erasureShort retention (7 days) on raw topics; compacted topics with personal data support deletion by key (tombstone)
AuditAdmin operations and ACL changes logged to the security log store
Threat analysisProducer impersonation, topic flooding, data exfiltration through consumer groups; recorded in security/threat-model

Assess personal data processing in the DPIA (compliance/dpia) when events feed profiling such as fraud scoring.

14. Operations and lag monitoring

SignalThreshold (Example)Action
Consumer lag in seconds (event time of last processed record versus now)Above 2 times the latency objective for 5 minutesPage on-call; check backpressure and sink health
Checkpoint durationAbove 50 % of the intervalInvestigate state growth and storage
Checkpoint failures3 in a rowPage on-call
Job restartsMore than 3 per hourPage on-call
Dead-letter rateAbove 0.1 % of inputNotify producer owner
Under-replicated partitionsAny for 5 minutesPlatform on-call
Schema registration rejectedAnyNotify producer owner

Write signal definitions and dashboards in the Observability Specification (ops/observability-spec) and runbooks for lag, failed checkpoints, DLQ replay and savepoint restore in dev/runbook.

15. Testing

IDTestMethodPass criterion
STT-001 (Example)Operator logicUnit tests with a test harness that controls timeExpected outputs for in-order, out-of-order and late events
STT-002 (Example)Contract compatibilitySchema check in CI against the registryNo incompatible change merged
STT-003 (Example)Exactly-once under failureKill task managers and brokers during a replay of known dataOutput equals expected with no duplicates or gaps
STT-004 (Example)LoadReplay of a peak day at 1.5 times rateLag stable, latency objectives met
STT-005 (Example)ReconciliationDaily compare of stream totals with source system totalsWithin 0.5 % (SRQ-001)
STT-006 (Example)UpgradeSavepoint, upgrade, restore in stagingState restored, no lost events
[STT-NNN][Test][Method][Criterion]

16. Trade-offs, roadmap and risks

16.1 Trade-offs

DecisionChosen (Example)AlternativeWhy chosenRevisit when
ProcessorFlink-style engine with event time and managed stateBroker-native stream librarySeveral input topics, large state, event-time windowsUse cases become simple per-topic transforms
Stock outputCompacted topic plus cacheDirect writes to the cacheReplayable, decouples consumersCache supports change streams natively
Fraud pathAt-least-once with idempotent receiverTransactional sink2-second objectiveCheckpoint interval can drop below 1 second
HostingManaged streaming serviceSelf-managed clusterOperations effortCost at ten times volume exceeds a dedicated team

16.2 Roadmap and risks

IncrementScopeExit criterion
S1 (Example)Sales and stock topics, bronze sinkReconciliation within 0.5 % for 4 weeks
S2 (Example)Stock availability job and cacheSUC-001 objective met in production
S3 (Example)Fraud scoringFalse positive rate agreed with risk team
IDRiskLikelihoodImpactResponseOwner
RSK-001 (Example)Hot partition from a flagship storeMediumMediumKey salting for that store or a finer key@streaming-architect
RSK-002 (Example)Schema change breaks consumersMediumHighRegistry enforcement, STT-002 in CI@platform-owner
RSK-003 (Example)State growth slows checkpointsMediumHighTTL on all state, checkpoint alert@sre-lead
[RSK-NNN][Risk][L / M / H][L / M / H][Response][@owner]

17. Glossary and references

TermMeaning
Event timeTime at which the event happened at the source
WatermarkMarker asserting that no earlier events are expected, which lets windows close
Allowed latenessExtra time during which late events still update a closed window
CheckpointConsistent snapshot of operator state and input positions used for recovery
SavepointUser-triggered snapshot used for upgrades, rescaling and migration
Compacted topicTopic that keeps at least the latest record per key
Consumer lagHow far a consumer is behind the end of a partition, in records or time
Effectively-onceEach input affects the results exactly once despite retries and restarts
Outbox patternWriting an event to a database table in the same transaction as the state change, then publishing it
ReferenceVersion or date checkedUse
AsyncAPI Specification, asyncapi.com3.1.0, released 2026-01-31, checked 2026-10-23Event contracts (section 4)
CloudEvents, cloudevents.io (CNCF)1.0.2Envelope attributes
Apache Kafka documentation and upgrade notes, kafka.apache.org4.3 line (4.3.1 released 2026-06-25); KRaft only since 4.0; share groups production-ready since 4.2; checked 2026-10-23Platform concepts
Apache Flink documentation, flink.apache.org2.3.0 (2026-06-25); 1.20 is the LTS line; checked 2026-10-23Time, watermarks, windows, exactly-once Kafka sink
Schema registry documentation (for example Confluent Schema Registry, docs.confluent.io)Checked 2026-10-23Compatibility mode names
[Managed service documentation][Version][Limits and quotas]

Standard and licence note

Based on the AsyncAPI Specification 3.1.0 (Linux Foundation, Apache License 2.0) for event contracts and CloudEvents 1.0.2 (CNCF) for event envelopes, with concepts described from the public Apache Kafka and Apache Flink documentation (Apache License 2.0). The text and the worked design are original and no documentation text is reproduced. This template is original text written for this collection. Check the current official versions of each specification and product before use. Apache Kafka and Apache Flink are trademarks of the Apache Software Foundation, and Confluent is a trademark of its owner; this template is not affiliated with or endorsed by them. Template licence: MIT.

Modèles associés