All labs ยท intermediate ยท about 30 min
๐ณ Billing charged some customers twice
The billing reader works through the shared notebook of orders. Some customers were charged twice, and after a restart one order was never charged at all. Find out why and fix it.
Java 21Kafka clientJUnit 5Practises๐ฌ Apache Kafka๐ Idempotency
๐จ The incident
Checkout writes a note in the shared notebook for every order, and the billing reader charges the card for each note. The billing reader already keeps a list of notes it has handled, so nothing should be charged twice. Yet on Tuesday support heard from two unhappy groups: a customer charged twice for one order, and a customer whose order was never charged at all, right after the billing reader tripped and was replaced. Your job: make every order be charged exactly once, whatever happens.
๐ What people saw
- The same order shows up twice on the customer's card, a few seconds apart.
- Checkout's log says it wrote the note for that order again because the first try seemed to get no answer.
- Right after the billing reader was replaced, one order in the middle of a pile was never charged.
[checkout] WARN send timed out for order=o-1042, retrying (attempt 2) [billing] INFO charge order=o-1041 amount=2500 offset=40 [billing] INFO charge order=o-1042 amount=3100 offset=41 [billing] INFO charge order=o-1042 amount=3100 offset=42 [billing] INFO charge order=o-1043 amount=800 offset=43 ... [billing] INFO charge order=o-1 amount=1200 offset=0 [billing] INFO charge order=o-2 amount=450 offset=1 [billing] INFO charge order=o-3 amount=990 offset=2 [billing] ERROR card processor call failed: billing pod killed [billing] INFO partitions assigned after restart: orders-0 from offset 0 [billing] INFO skip duplicate order=o-1 offset=0 [billing] INFO skip duplicate order=o-2 offset=1 [billing] INFO skip duplicate order=o-3 offset=2
โถ๏ธ Start the lab
- Unzip it and open the
kafka-double-chargefolder in your editor. - Run
mvn test. The failing tests are the bug report: read what they expect. - Fix the code in
src/mainuntilmvn testpasses. Leave the tests alone: they describe what the system must guarantee.
๐ Start reading here
src/main/java/lab/billing/BillingWorker.java
1package lab.billing;23import java.time.Duration;4import java.util.List;5import org.apache.kafka.clients.consumer.Consumer;6import org.apache.kafka.clients.consumer.ConsumerRecord;7import org.slf4j.Logger;8import org.slf4j.LoggerFactory;910/**11* Reads "order placed" events from the orders topic and charges each order once.12* Record key: the order id. Record value: the amount in cents.13*/14public class BillingWorker {15private static final Logger log = LoggerFactory.getLogger(BillingWorker.class);1617private final Consumer<String, String> consumer;18private final PaymentGateway payments;19private final ProcessedStore processed;2021public BillingWorker(Consumer<String, String> consumer, PaymentGateway payments, ProcessedStore processed) {22this.consumer = consumer;23this.payments = payments;24this.processed = processed;25}2627public void subscribe() {28consumer.subscribe(List.of("orders"));29}3031/** Polls one batch, charges every new order in it, then commits the batch's offsets. */32public void pollOnce() {33for (ConsumerRecord<String, String> rec : consumer.poll(Duration.ofMillis(100))) {34String dedupKey = rec.topic() + "-" + rec.partition() + "-" + rec.offset();35if (!processed.claim(dedupKey)) {36log.info("skip duplicate order={} offset={}", rec.key(), rec.offset());37continue;38}39log.info("charge order={} amount={} offset={}", rec.key(), rec.value(), rec.offset());40payments.charge(rec.key(), Long.parseLong(rec.value()));41}42consumer.commitSync();43}44}
src/main/java/lab/billing/ProcessedStore.java
1package lab.billing;23import java.util.Set;4import java.util.concurrent.ConcurrentHashMap;56/**7* Remembers which messages billing has already handled. In production this is a table with a unique key;8* here it is in memory, and it survives a worker restart because the test passes the same instance in.9*/10public class ProcessedStore {11private final Set<String> seen = ConcurrentHashMap.newKeySet();1213/** Returns true the first time a key is claimed, false every time after. */14public boolean claim(String key) {15return seen.add(key);16}1718/** Gives a claimed key back, so the message can be handled again later. */19public void release(String key) {20seen.remove(key);21}22}
src/test/java/lab/billing/BillingWorkerTest.java
1package lab.billing;23import static org.junit.jupiter.api.Assertions.assertEquals;45import java.util.ArrayList;6import java.util.HashMap;7import java.util.List;8import java.util.Map;9import org.apache.kafka.clients.consumer.ConsumerRecord;10import org.apache.kafka.clients.consumer.MockConsumer;11import org.apache.kafka.clients.consumer.internals.AutoOffsetResetStrategy;12import org.apache.kafka.common.TopicPartition;13import org.junit.jupiter.api.Test;1415class BillingWorkerTest {16static final TopicPartition ORDERS = new TopicPartition("orders", 0);1718/** Records every charge instead of taking money. */19static class RecordingGateway implements PaymentGateway {20final List<String> charges = new ArrayList<>();21int failAfter = Integer.MAX_VALUE;2223@Override24public void charge(String orderId, long amountCents) {25if (charges.size() == failAfter) throw new IllegalStateException("billing pod killed");26charges.add(orderId);27}28}2930static MockConsumer<String, String> consumerFrom(long offset) {31var consumer = new MockConsumer<String, String>(AutoOffsetResetStrategy.EARLIEST.name());32consumer.subscribe(List.of("orders"));33consumer.rebalance(List.of(ORDERS));34consumer.updateBeginningOffsets(Map.of(ORDERS, offset));35return consumer;36}3738static void send(MockConsumer<String, String> consumer, long offset, String orderId, String cents) {39consumer.addRecord(new ConsumerRecord<>("orders", 0, offset, orderId, cents));40}4142static Map<String, Integer> counts(List<String> charges) {43Map<String, Integer> counts = new HashMap<>();44charges.forEach(id -> counts.merge(id, 1, Integer::sum));45return counts;46}4748@Test49void aCrashMidBatchNeitherLosesNorRepeatsACharge() {50var gateway = new RecordingGateway();51var store = new ProcessedStore();5253// First worker charges o-1 and o-2, then dies while charging o-3, before it can commit.54var first = consumerFrom(0);55send(first, 0, "o-1", "1200");56send(first, 1, "o-2", "450");57send(first, 2, "o-3", "990");58gateway.failAfter = 2;59try {60new BillingWorker(first, gateway, store).pollOnce();61} catch (IllegalStateException crashed) {62// nothing was committed63}6465// Kafka hands the same three records to the replacement worker.66gateway.failAfter = Integer.MAX_VALUE;67var second = consumerFrom(0);68send(second, 0, "o-1", "1200");69send(second, 1, "o-2", "450");70send(second, 2, "o-3", "990");71new BillingWorker(second, gateway, store).pollOnce();7273assertEquals(Map.of("o-1", 1, "o-2", 1, "o-3", 1), counts(gateway.charges),74"every order must be charged exactly once, even across a crash");75}7677@Test78void anOrderSentTwiceByTheCheckoutServiceIsChargedOnce() {79var gateway = new RecordingGateway();80var consumer = consumerFrom(40);81// Checkout's send timed out, so it retried: o-1042 is in the topic twice, at offsets 41 and 42.82send(consumer, 40, "o-1041", "2500");83send(consumer, 41, "o-1042", "3100");84send(consumer, 42, "o-1042", "3100");85send(consumer, 43, "o-1043", "800");8687new BillingWorker(consumer, gateway, new ProcessedStore()).pollOnce();8889assertEquals(Map.of("o-1041", 1, "o-1042", 1, "o-1043", 1), counts(gateway.charges),90"each order must be charged exactly once");91}92}
๐ก Hints
โ What really happened
Fixed it? Or completely stuck? Either way, here's what really happened.