Batch and Stream: Monthly Settlement Reports and a Live Trending List, Two Ways to Process Data
System Design series · Part 7 Architecture evolution (4 of 4)
- Monolith vs Microservices: Get the Boundaries Right Before You Decide Whether to Split
- Service Discovery: How Services Find Each Other, and What Happens When an Instance Disappears
- Sagas and the Outbox Pattern: Keeping a Cross-Service Flow Consistent Without Distributed Transactions
- Batch and Stream: Monthly Settlement Reports and a Live Trending List, Two Ways to Process Data
System Design series Part 7-4 | Previous: Sagas and the Outbox Pattern | Next: Authentication: Sessions, Tokens, and OAuth 2.0/OIDC | Series map
Read first: Part 5-3 Pub/Sub and Delivery Semantics.
Scenario and problem
The talk platform has two new requirements:
- Monthly speaker settlement: on the 1st of every month, compute each speaker’s revenue share from last month’s confirmed sign-ups, create settlement records, and hand them to the payment flow for payout. 5,000 speakers and 1 million sign-ups last month
- Live trending list: the home page shows “the talks with the most sign-ups in the past minute”, and the moment sign-ups open, it has to reflect them within a few seconds
Both work on the same sign-up data, but what they need is completely different. The monthly settlement has to be correct: a few hours late is fine, but paying the wrong amount or paying twice is not. The trending list has to be fast: if it occasionally misses a sign-up or two, users will not notice.
- Monthly speaker settlementOn the 1st of every month, compute the revenue share of 5,000 speakers from last month's confirmed sign-ups, create settlement records, and hand them to the payment flow for payout.
- Live trending listThe home page shows the talks with the most sign-ups in the past minute, and the moment sign-ups open, it has to reflect them within a few seconds.
- Correct, or fastThe monthly settlement has to be correct: a few hours late is fine, but paying the wrong amount or paying twice is not. The trending list has to be fast: if it occasionally misses a sign-up or two, users will not notice.
This is the dividing line between batch and stream processing: is the data bounded (last month’s sign-ups, which will not change anymore) or unbounded (sign-ups keep pouring in, and there is never a moment when “everything has arrived”)?
The simplest approach and its limits
Monthly settlement: run a script against the production database at midnight
List<Speaker> speakers = speakerRepository.findAll(); // load everything at once
for (Speaker s : speakers) {
BigDecimal income = registrationRepository.sumIncome(s.id(), month);
settlementRepository.save(new Settlement(s.id(), month, income));
}- It runs on the primary, and the settlement’s heavy queries slow down the sign-up transactions running at the same time
- The process crashes at the 4,000th speaker. Rerunning it starts from the beginning: will the settlement records already written for the first 4,000 be duplicated?
- Someone accidentally runs it again on the same day: will speakers be paid twice?
Trending list: query the database on every request
SELECT lecture_id, COUNT(*) FROM registration
WHERE created_at > NOW() - INTERVAL 1 MINUTE
GROUP BY lecture_id ORDER BY COUNT(*) DESC LIMIT 10;The home page is viewed thousands of times a second, and every view runs an aggregate query on the hottest table. Right when sign-ups open and the database is at its busiest.
Core mechanism
Batch: bounded data, so the focus is restartability and idempotency
The input to batch processing is fixed: last month’s sign-ups will not change again. That lets it focus on throughput and correctness:
Chunked processing (chunk): read N records at a time, process them, write them, then commit one transaction and record how far you have gotten.
- Transactions stay small: writing 1 million rows at once will not lock the table for a long time or blow up the undo log
- After a crash, you continue from the last committed position instead of starting over
Use keyset pagination, not OFFSET: LIMIT 1000 OFFSET 900000 has to scan the first 900,000 rows and then throw them away. Split 1 million rows into 1,000 pages and each page skips 500,000 rows on average, about 500 million rows scanned in total; with WHERE id > :lastId ORDER BY id LIMIT 1000, every page goes straight to its position in the index, and only 1 million rows are scanned in total (the Indexes and B+Trees post).
Output must be idempotent: rerunning the settlement for the same month should give exactly the same result, not an extra copy. Settlement records use (speaker_id, settle_month) as a unique key, and writes are upserts. The actual payout is a separate step with its own idempotency protection (the payout flow in the Distributed Locks and Fencing Tokens post).
The same input runs only once: “the October 2026 settlement” is a well-defined job instance. An instance that has already completed successfully should not run again; a failed instance should continue from where it stopped.
The data you read needs a clear cutoff: the settlement reads “sign-ups confirmed between 00:00 on October 1 and 00:00 on November 1”, not “all sign-ups in the database right now”. When it runs on a replica, first confirm that replication has caught up past the cutoff (the Replication and Replication Lag post).
Stream: unbounded data, so the focus is time
The input to stream processing keeps growing forever. “How many sign-ups in the past minute” sounds simple, but there is a fundamental question: whose time is “one minute”?
- Event time: when the sign-up actually happened, recorded in the event
- Processing time: when the stream application gets to the event
Normally the two differ by only a few milliseconds. But a phone loses its connection on the MRT and sends the sign-up 30 seconds later; the consumer of one partition restarts and builds up a 2-minute backlog. Counted by processing time, these events land in the wrong minute.
Windows cut unbounded data into bounded pieces:
| Window | How it splits | Example |
|---|---|---|
| Tumbling window | Fixed size, no overlap | Sign-ups per minute: 10:00–10:01, 10:01–10:02 |
| Hopping window | Fixed size, overlapping | Update the “past minute” sign-up count every 10 seconds |
| Session window | Split by gaps in activity | A user keeps browsing talks; 30 minutes idle ends a session |
Late data: when does the 10:00–10:01 window “end”? If it ends the moment the clock reaches 10:01, an event that happened at 10:00:50 but arrived at 10:01:20 is missed. So a window needs a grace period: late events that arrive within it are still counted, and events that arrive after it are dropped. The longer the grace period, the more complete the result, but the later the final result comes out and the more state you have to keep.
State: counts and aggregates need to keep intermediate state. When a stream application restarts or its partitions are reassigned, the state must not be lost. Kafka Streams keeps state locally, also writes it to a Kafka changelog topic, and restores it from there on restart.
Lambda and Kappa
| Architecture | How | Cost |
|---|---|---|
| Lambda | The same data goes down two paths at once, batch and stream: the stream gives real-time but possibly inexact results, and the batch periodically produces exact results that overwrite them | The same logic is written twice and maintained twice, and the results from the two sides may not match |
| Kappa | Stream only. When you need to recompute (changed logic, a bug fix), replay from the start of the retained log | Depends on an event log retained for a long time; replaying a lot of history takes time and resources |
Kappa assumes the events are fully retained (the Kafka log in the Pub/Sub and Delivery Semantics post) and that the stream application itself can produce exact results. In practice many systems are hybrids: stream for real-time metrics, batch for results that involve money and need auditing and reconciliation.
Comparing options
| Batch | Stream | |
|---|---|---|
| Input | Bounded: a day, a month | Unbounded: keeps arriving |
| Latency | Minutes to hours | Milliseconds to seconds |
| Correctness | Fixed input, easy to rerun and easy to verify | Has to handle out-of-order, late, and duplicate events |
| Failure handling | Restart from a checkpoint | State must be recoverable, and output must handle duplicates |
| Good for | Settlement, reconciliation, reports, data migration, rebuilding indexes | Real-time metrics, anomaly detection, real-time recommendations, notifications |
The talk platform’s choice: Spring Batch for the monthly speaker settlement, reading from a replica and writing settlement records to the primary; Kafka Streams for the trending list, consuming sign-up events and writing the results to another topic, which the push service from the Real-Time Updates post sends to the browser.
In Java
1. Monthly settlement: chunked processing in Spring Batch
CREATE TABLE speaker_settlement (
speaker_id BIGINT NOT NULL,
settle_month CHAR(7) NOT NULL, -- e.g. 2026-10
gross DECIMAL(12,2) NOT NULL,
payout DECIMAL(12,2) NOT NULL,
PRIMARY KEY (speaker_id, settle_month)
);@Configuration
public class SpeakerSettlementJobConfig {
@Bean
Job speakerSettlementJob(JobRepository jobRepository, Step settleSpeakers) {
return new JobBuilder("speakerSettlement", jobRepository)
.start(settleSpeakers)
.build();
}
@Bean
Step settleSpeakers(JobRepository jobRepository, PlatformTransactionManager transactionManager,
JdbcPagingItemReader<SpeakerShare> speakerReader,
SettlementCalculator calculator,
JdbcBatchItemWriter<Settlement> settlementWriter) {
return new StepBuilder("settleSpeakers", jobRepository)
.<SpeakerShare, Settlement>chunk(200).transactionManager(transactionManager)
.reader(speakerReader)
.processor(calculator)
.writer(settlementWriter)
.build();
}
@Bean
@StepScope
JdbcPagingItemReader<SpeakerShare> speakerReader(@Qualifier("replicaDataSource") DataSource replica) {
return new JdbcPagingItemReaderBuilder<SpeakerShare>()
.name("speakerReader") // used to save the read position in the ExecutionContext
.dataSource(replica)
.selectClause("SELECT id, revenue_share")
.fromClause("FROM speaker")
.sortKeys(Map.of("id", Order.ASCENDING)) // keyset pagination; the sort key must be unique
.rowMapper((rs, rowNum) -> new SpeakerShare(rs.getLong("id"), rs.getBigDecimal("revenue_share")))
.pageSize(200)
.build();
}
@Bean
JdbcBatchItemWriter<Settlement> settlementWriter(DataSource primary) {
return new JdbcBatchItemWriterBuilder<Settlement>()
.dataSource(primary)
.sql("""
INSERT INTO speaker_settlement (speaker_id, settle_month, gross, payout)
VALUES (:speakerId, :settleMonth, :gross, :payout) AS incoming
ON DUPLICATE KEY UPDATE gross = incoming.gross, payout = incoming.payout
""")
.itemSqlParameterSourceProvider(SimplePropertySqlParameterSource::new)
.build();
}
}@Component
@StepScope
public class SettlementCalculator implements ItemProcessor<SpeakerShare, Settlement> {
private final JdbcClient replica;
private final YearMonth month;
public SettlementCalculator(@Qualifier("replicaJdbcClient") JdbcClient replica,
@Value("#{jobParameters['month']}") String month) {
this.replica = replica;
this.month = YearMonth.parse(month);
}
@Override
public Settlement process(SpeakerShare speaker) {
BigDecimal gross = replica.sql("""
SELECT COALESCE(SUM(r.amount), 0)
FROM registration r JOIN lecture l ON l.id = r.lecture_id
WHERE l.speaker_id = :speakerId AND r.status = 'CONFIRMED'
AND r.confirmed_at >= :from AND r.confirmed_at < :to
""")
.param("speakerId", speaker.id())
.param("from", month.atDay(1).atStartOfDay())
.param("to", month.plusMonths(1).atDay(1).atStartOfDay())
.query(BigDecimal.class)
.single();
if (gross.signum() == 0) {
return null; // returning null means no settlement for this speaker; nothing is written
}
BigDecimal payout = gross.multiply(speaker.revenueShare()).setScale(2, RoundingMode.HALF_UP);
return new Settlement(speaker.id(), month.toString(), gross, payout);
}
}- Restarting and preventing duplicate runs both depend on the execution records that the job repository keeps. Spring Batch 6’s default
ResourcelessJobRepositorykeeps no records at all and only suits one-off jobs; the monthly settlement has to use a JDBC job repository instead (Spring Boot’s JDBC store, or@EnableJdbcJobRepository) monthis an identifying parameter: once the job instance formonth=2026-10has completed successfully, Spring Batch rejects another launch with the same parameter; a failed instance, when launched again, continues from the last committed chunk- Every time a chunk commits,
JdbcPagingItemReadersaves the last row’s sort key in theExecutionContext, and on restart it reads from after that key - Even if someone bypasses Spring Batch and reruns the job,
ON DUPLICATE KEY UPDATEgives the same result, so no extra settlement appears - Always use
BigDecimalfor amounts, neverdouble - Reads go to the replica, writes go to the primary. Before starting, check the replica’s replication lag to make sure everything before the cutoff has been replicated
2. Trending list: tumbling windows in Kafka Streams
spring:
kafka:
streams:
application-id: trending-lectures # also the consumer group ID and the prefix of internal topics
properties:
"[processing.guarantee]": exactly_once_v2@Configuration
@EnableKafkaStreams
public class TrendingLecturesTopology {
@Bean
KStream<String, RegistrationEvent> registrationsPerMinute(StreamsBuilder builder,
Serde<RegistrationEvent> registrationSerde,
Serde<LectureRate> rateSerde) {
KStream<String, RegistrationEvent> events =
builder.stream("registration-events", Consumed.with(Serdes.String(), registrationSerde));
events.filter((key, event) -> event.type() == RegistrationEvent.Type.CONFIRMED)
// the original key is the registration ID; grouping by lecture ID makes Kafka Streams create an internal repartition topic
.groupBy((key, event) -> String.valueOf(event.lectureId()),
Grouped.with(Serdes.String(), registrationSerde))
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofMinutes(1), Duration.ofSeconds(30)))
.count(Materialized.as("registrations-per-minute"))
.toStream()
.map((window, count) -> KeyValue.pair(window.key(),
new LectureRate(window.key(), window.window().startTime(), count)))
.to("lecture-registration-rate", Produced.with(Serdes.String(), rateSerde));
return events;
}
}- Windows are computed by event time: by default that is the timestamp on the Kafka record, the time the producer sent it. To use a field inside the event, write a custom
TimestampExtractor - A 30-second grace period: the 10:00–10:01 window closes after 10:01:30 (in stream time), and events that arrive later are dropped. The trending list can accept that; the monthly settlement cannot, which is one of the reasons the settlement uses batch
- Each incoming event updates the window’s count and sends it downstream. That continuously updated result is exactly what the trending list needs; if downstream only wants the final result (for example, to send an alert), add
suppress(Suppressed.untilWindowCloses(...)) exactly_once_v2guarantees that “reading the sign-up event, updating the count state, and writing to the result topic” are atomic inside Kafka; consumers that readlecture-registration-ratehave to setisolation.level=read_committed. It does not cover external side effects (the Pub/Sub and Delivery Semantics post)- The
Serdedefinitions are omitted; the retention period ofregistration-eventsdecides how far back a “recompute” can go
The code above is written from the official documentation for Spring Batch 6, Spring Boot 4.1, Spring for Apache Kafka, and Apache Kafka 4.3, and has not been compiled or run. The SQL uses MySQL 8.0.19+ syntax as the example.
Pitfalls and gotchas
- Paging a batch with OFFSET: every page is slower than the one before, and the total cost is quadratic
- A non-unique sort key in a batch: sort by
created_at, and when two rows from the same millisecond fall right on a page boundary, one of them is skipped or read twice - Non-idempotent batch output: after a restart, chunks that were already committed are written again
- Running the batch on the primary: the heavy reads slow down online transactions
- Reading “current” data instead of a fixed cutoff: the settlement runs in the early hours of the 1st, and the result includes sign-ups from the early hours of the 1st
- Using processing time in a stream: when consumers fall behind or restart, events land in the wrong window
- A grace period that is too short or too long: too short, and lots of late events are dropped; too long, and the state grows and results are delayed
- Ignoring the cost of repartitioning:
groupBychanges the key, so every event is written to and read from an internal topic one more time. With large volumes, the producer can use the key the grouping needs from the start and skip this step - Assuming replay is free: when a Kappa architecture recomputes, every side effect (notifications, writes to external systems) happens again; those downstream systems must be idempotent, or be switched off during the replay
- Using stream results for reconciliation: results that involve money and need auditing should be recomputed by a batch from the source of truth, not built by adding up the stream’s intermediate results
Security
- Batch jobs usually have too much access: the settlement needs to read every sign-up, and a common shortcut is to give it a database account that can do anything. It actually needs only read-only access to the replica and write access to the settlement table. If a batch job’s account is stolen, all of the data is exposed
- Protect the interface that triggers batches: when a batch is started from an HTTP endpoint or an admin UI, no authentication means anyone can rerun the settlement, trigger payouts, or start heavy queries at peak time and bring the database down
- Never concatenate job parameters into SQL: building a
whereClausedynamically from job parameters is SQL injection. Always use named parameters - Batch output is a bulk data export: the generated CSVs and report files, left in shared storage, are a complete copy of personal or financial data. Encrypt them, restrict access, set a retention period, and record who downloaded them (the audit logs in the Observability post)
- A forged timestamp closes other people’s windows: Kafka Streams advances stream time by the largest timestamp it has seen. An attacker who can write to the topic sends one event with a timestamp an hour in the future, stream time jumps an hour ahead, and every normal event after that is treated as late and dropped. Restrict who can write to the source topic (ACLs), check that timestamps fall in a reasonable range where events are produced, or have the topic use the broker’s append time (
LogAppendTime) - One broken event stops the whole stream: the default handling for a deserialization failure is to stop. Anyone who can write to the topic only has to send one malformed message to stop the trending list from updating. Configure explicitly what happens when deserialization fails (log and skip, or send to a DLQ), and monitor how many events are skipped
- State and internal topics hold data too: Kafka Streams’ local state (RocksDB files), changelog topics, and repartition topics all contain event contents. Internal topics need ACLs, local disks need encryption, and personal data the stream does not need should stay out of the events
- Watch for permission changes when you replay old data: when you replay events from three months ago, some users have deleted their accounts and some speakers have been suspended. Recomputed results should not make deleted personal data reappear in a new system
When to use it, and when not to
- Use batch: the input has a clear boundary, the result must be exact, and minutes to hours of latency is acceptable: settlement, reconciliation, reports, data migration, rebuilding search indexes
- Use stream: you need to react within seconds and can accept approximate or continuously corrected results: real-time metrics, anomaly detection, real-time recommendations, notifications
- When to re-evaluate: the batch’s run time approaches the interval between runs (an hourly batch takes 50 minutes), or the business starts asking to “see the settlement numbers in real time too”
- Don’t use stream: for small data and reports that only need computing once a day, a scheduled SQL query or a batch is enough; a streaming framework’s state, partitions, reassignment, and late data are all complexity that someone has to operate
References
- Tyler Akidau, “Streaming 101” and “Streaming 102”, O’Reilly Radar, 2015–2016: https://www.oreilly.com/radar/the-world-beyond-batch-streaming-101/
- Tyler Akidau, Slava Chernyak, Reuven Lax, Streaming Systems, O’Reilly, 2018
- Jay Kreps, “Questioning the Lambda Architecture”, O’Reilly Radar, 2014: https://www.oreilly.com/radar/questioning-the-lambda-architecture/
- Martin Kleppmann, Designing Data-Intensive Applications, O’Reilly, 2017, Chapter 10 “Batch Processing” and Chapter 11 “Stream Processing”
- Spring Batch Reference Documentation (Chunk-oriented Processing, JdbcPagingItemReader, Restartability): https://docs.spring.io/spring-batch/reference/
- Apache Kafka Documentation — Kafka Streams Developer Guide (Windowing, Window Final Results): https://kafka.apache.org/documentation/streams/developer-guide/dsl-api.html
- Spring for Apache Kafka Reference — Apache Kafka Streams Support: https://docs.spring.io/spring-kafka/reference/streams.html
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments