Skip to content
Interview rounds

Concurrency & payments · Bug Squash (Java)

The hit counter that counts low

A Java class counts API calls per key from many request threads, and its totals come out low. Where is the bug?

BackendMid10 min
Interview-style scenarioLast reviewed: Checked against official documentation

Bug Squash · Java 21 · HitCounter.javaIllustrative scenario, not a real incident

Billed API calls are about 2.5% below the access log for the busiest key

A payments API bills each merchant per call. HitCounter counts the calls per API key in memory, and a billing job reads the counts.

Last week the server went from 2 request threads to 32. Since then the count for the busiest key has been lower than the access log says. A test that reproduces it is below. No code runs in your browser: read it as you would in a review.

What the dashboards and logs show

Expected
320,000 hits for key-A and 320,000 in total
Actual
311,842 for key-A and 316,507 in total, different on every run
With one thread
the same test passes every time
Exceptions
none in this run

Find the bug · scored under "Hypothesis before change"

Tap the faulty lines

The test below fails. Mark up to 3 lines you would change, then check them. There are 3. A wrong mark costs half a line.

Failing test · countsEveryHitFromManyThreads
HitCounterTest > countsEveryHitFromManyThreads() FAILED
    org.opentest4j.AssertionFailedError:
    32 threads x 10,000 calls to record("key-A")
    hits("key-A") expected: <320000> but was: <311842>
    total()       expected: <320000> but was: <316507>

1 test completed, 1 failed
HitCounter.java

No line marked yet

Your rubric score, the model answer, the follow-up questions and the related lessons appear once you have answered the last step.