TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

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 5

Practises๐Ÿ“ฌ 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

โฌ‡ Download the projectNeeds Java 21 and Maven.
  1. Unzip it and open the kafka-double-charge folder in your editor.
  2. Run mvn test. The failing tests are the bug report: read what they expect.
  3. Fix the code in src/main until mvn test passes. Leave the tests alone: they describe what the system must guarantee.

๐Ÿ“‚ Start reading here

src/main/java/lab/billing/BillingWorker.java
1package lab.billing;2 3import 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;9 10/**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 {15    private static final Logger log = LoggerFactory.getLogger(BillingWorker.class);16 17    private final Consumer<String, String> consumer;18    private final PaymentGateway payments;19    private final ProcessedStore processed;20 21    public BillingWorker(Consumer<String, String> consumer, PaymentGateway payments, ProcessedStore processed) {22        this.consumer = consumer;23        this.payments = payments;24        this.processed = processed;25    }26 27    public void subscribe() {28        consumer.subscribe(List.of("orders"));29    }30 31    /** Polls one batch, charges every new order in it, then commits the batch's offsets. */32    public void pollOnce() {33        for (ConsumerRecord<String, String> rec : consumer.poll(Duration.ofMillis(100))) {34            String dedupKey = rec.topic() + "-" + rec.partition() + "-" + rec.offset();35            if (!processed.claim(dedupKey)) {36                log.info("skip duplicate order={} offset={}", rec.key(), rec.offset());37                continue;38            }39            log.info("charge order={} amount={} offset={}", rec.key(), rec.value(), rec.offset());40            payments.charge(rec.key(), Long.parseLong(rec.value()));41        }42        consumer.commitSync();43    }44}
src/main/java/lab/billing/ProcessedStore.java
1package lab.billing;2 3import java.util.Set;4import java.util.concurrent.ConcurrentHashMap;5 6/**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 {11    private final Set<String> seen = ConcurrentHashMap.newKeySet();12 13    /** Returns true the first time a key is claimed, false every time after. */14    public boolean claim(String key) {15        return seen.add(key);16    }17 18    /** Gives a claimed key back, so the message can be handled again later. */19    public void release(String key) {20        seen.remove(key);21    }22}
src/test/java/lab/billing/BillingWorkerTest.java
1package lab.billing;2 3import static org.junit.jupiter.api.Assertions.assertEquals;4 5import 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;14 15class BillingWorkerTest {16    static final TopicPartition ORDERS = new TopicPartition("orders", 0);17 18    /** Records every charge instead of taking money. */19    static class RecordingGateway implements PaymentGateway {20        final List<String> charges = new ArrayList<>();21        int failAfter = Integer.MAX_VALUE;22 23        @Override24        public void charge(String orderId, long amountCents) {25            if (charges.size() == failAfter) throw new IllegalStateException("billing pod killed");26            charges.add(orderId);27        }28    }29 30    static MockConsumer<String, String> consumerFrom(long offset) {31        var consumer = new MockConsumer<String, String>(AutoOffsetResetStrategy.EARLIEST.name());32        consumer.subscribe(List.of("orders"));33        consumer.rebalance(List.of(ORDERS));34        consumer.updateBeginningOffsets(Map.of(ORDERS, offset));35        return consumer;36    }37 38    static void send(MockConsumer<String, String> consumer, long offset, String orderId, String cents) {39        consumer.addRecord(new ConsumerRecord<>("orders", 0, offset, orderId, cents));40    }41 42    static Map<String, Integer> counts(List<String> charges) {43        Map<String, Integer> counts = new HashMap<>();44        charges.forEach(id -> counts.merge(id, 1, Integer::sum));45        return counts;46    }47 48    @Test49    void aCrashMidBatchNeitherLosesNorRepeatsACharge() {50        var gateway = new RecordingGateway();51        var store = new ProcessedStore();52 53        // First worker charges o-1 and o-2, then dies while charging o-3, before it can commit.54        var first = consumerFrom(0);55        send(first, 0, "o-1", "1200");56        send(first, 1, "o-2", "450");57        send(first, 2, "o-3", "990");58        gateway.failAfter = 2;59        try {60            new BillingWorker(first, gateway, store).pollOnce();61        } catch (IllegalStateException crashed) {62            // nothing was committed63        }64 65        // Kafka hands the same three records to the replacement worker.66        gateway.failAfter = Integer.MAX_VALUE;67        var second = consumerFrom(0);68        send(second, 0, "o-1", "1200");69        send(second, 1, "o-2", "450");70        send(second, 2, "o-3", "990");71        new BillingWorker(second, gateway, store).pollOnce();72 73        assertEquals(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    }76 77    @Test78    void anOrderSentTwiceByTheCheckoutServiceIsChargedOnce() {79        var gateway = new RecordingGateway();80        var consumer = consumerFrom(40);81        // Checkout's send timed out, so it retried: o-1042 is in the topic twice, at offsets 41 and 42.82        send(consumer, 40, "o-1041", "2500");83        send(consumer, 41, "o-1042", "3100");84        send(consumer, 42, "o-1042", "3100");85        send(consumer, 43, "o-1043", "800");86 87        new BillingWorker(consumer, gateway, new ProcessedStore()).pollOnce();88 89        assertEquals(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.