Originally published on Aws Builders — Read the original article
A customer looks up a Pix key, checks the recipient’s name, and closes the app. Days later, one integration is still sending lookups at its usual rate, with healthy latency and almost no payments. When would you open an investigation?
Pix is Brazil’s instant payment system. I worked on its architecture at my institution and helped build the rate limiter for key lookups. The tricky part was deciding when a lookup should spend a token and when a later payment should return one.
What a Pix lookup costs
A Pix key lets a payer look up a recipient without typing their bank account details. The institution queries a directory operated by Brazil’s central bank, known as DICT, so the payer can check who will receive the money. Repeated reads also create an opportunity to collect personal data. [1]
A token bucket with feedback from the payment
A token bucket holds a limited number of permits. An incoming request needs a permit to proceed. Tokens refill over time, which gives a customer room for a short burst of activity.
The DICT rules also account for what happens after admission. For an individual payer’s bucket, version 8.5 of the operating manual specifies these amounts. [1]
Key found: spend one token.
Key missing: spend 20 tokens in total.
Matching payment order received by SPI, the instant payment settlement system: return one token.
Business users and participating institutions have their own parameters. An institution’s internal controls must be at least as restrictive as the DICT rules. Our local proof of concept uses a smaller, fictional penalty so the balance is easy to trace.
Why we moved the balance out of the JVM
We started with Bucket4j in memory. With a single process, I could watch the balance fall after each request. With two replicas, each could spend what it believed was the same customer’s last token. Restarting a process could also hand the customer a full bucket. [2]
What mattered in the storage decision
We considered Redis, Apache Ignite, and Hazelcast. In the practical comparison with Ignite, our engineering and infrastructure teams chose Redis for this workload. Anderson Martins Silva and I described that evaluation in an earlier account.
Contention: how long does a command take when several requests compete for the same balance?
Java integration: how much work does it take to connect the existing Bucket4j application to shared state?
Recovery: after a node fails, can the team establish how many tokens the customer still has?
In production we watched command latency, connections, memory, and replication in Grafana. During a failover exercise, I would check the customer’s balance as soon as the application reconnected. A successful connection alone tells you little about which requests will be admitted next.
Two replicas race for the last token
To reproduce the decision locally, I used spec-driven development (SDD). I wrote the acceptance criterion before generating the Java implementation and its tests. Criterion ADM-03 ties a customer-visible response to a downstream effect that we can count. [7]
The test that makes the race observable
Give one synthetic identity a single token in Redis. Freeze the test clock so no refill can occur.
Send two concurrent POST /lookups requests, one to each replica. Use the same identity with different recipient IDs and different Idempotency-Key values.
Check both responses, the directory receipts, and the final balance. One request returned HTTP 200 and read its recipient once. The other returned HTTP 429 (Too Many Requests) before reaching the directory. The balance was zero. [8]
LastTokenTest lets either replica win. The replica that returned 200 must have read exactly its own recipient. The one that returned 429 must have an empty read list.
assertThat(codes).containsExactlyInAnyOrder(200, 429); assertThat(reads(first)) .containsExactlyElementsOf(codes.getFirst() == 200 ? List.of("found-a") : List.of()); assertThat(reads(second)) .containsExactlyElementsOf(codes.getLast() == 200 ? List.of("found-b") : List.of()); long remaining = balance(); assertThat(remaining).isZero(); We repeated the race with two Spring Boot containers sharing one Redis instance in Docker Compose. The directory receipt count moved from 20 to 21. Even without the test harness, we could see that exactly one additional read had occurred. [10]

Figure 1. Two replicas compete for one shared token. Only the admitted lookup reaches the directory.
What happens when a result arrives twice?
The service can reserve a token before a lookup, but it can charge for a missing key only after the directory replies. That gap matters if an event is redelivered or its consumer stops midway.
Follow one missing key from ten tokens to six
Start with 10 tokens. Reserve one before the read, leaving 9.
The directory reports a missing key. The fictional policy charges four in total, so debit three more. The balance is 6.
Redeliver the same result concurrently. The balance stays at 6, and the history contains one additional debit. [9]

Figure 2. Admission pays for the read. A conclusive miss triggers the extra charge.
A successful lookup left 9 tokens. A timeout also left 9, with an inconclusive result. A timeout tells us that a read was attempted. It tells us nothing about whether the key exists.
What survives a consumer restart
One Redis transaction commits the bucket state, the operation receipt, and the event. The consumer records completion afterward. When two confirmations arrived for the same eligible order, the balance moved from 8 to 9 just once. [9]
By this point in RedisLedger, Bucket4j has computed the new balance on a private copy. The transaction publishes that balance alongside its receipt and events. If another replica changes the watched account before EXEC, the operation retries.
try (Transaction tx = db.multi()) { if (snapshot != null) tx.hset(bytes(account), bytes("bucket"), snapshot); if (!change.fields.isEmpty()) tx.hset(account, change.fields); for (String event : change.events) tx.rpush("journey:events", event); tx.del(candidate); if (tx.exec() != null) return answer; } We injected a failure after a debit committed and before the consumer marked it complete. Further lookups for that identity returned HTTP 503 while another identity continued to work. After a restart with Redis preserved, the consumer recognized the receipt and released the identity with 8 tokens: the original 6 plus two scheduled refills. Losing Redis itself would require a separate recovery test.
Same lookup volume, different reasons to investigate
How many lookups find a key? How many lead to a payment order? We built two synthetic cases with the same 144 admitted lookups: two integrations, three ten-minute windows, and 24 lookups per integration per window. Both integrations confirmed 16 orders in the first window. [10]
Where did confirmations disappear?
After a simulated deployment, both integrations dropped to zero orders. Each logged 16 confirmation errors in each later window. I would compare confirmation traces across versions and check the shared dependency.
In the second case, Alpha had zero orders for two windows. Beta still confirmed 16 per window, and neither integration recorded confirmation errors. I would inspect Alpha’s client telemetry to see whether it ever attempted confirmation.

Figure 3. Each cell shows confirmed orders for 24 admitted lookups. Scope and persistence point to different next checks.
What to ask an investigation agent when orders disappear
Looking at those two charts, I would give an agent a narrow assignment: which trace should the on-call engineer open first, and why? Lookup volume held steady in both cases. The clue is which integration stopped confirming orders, on which version, and when.
How the agent gets its evidence
The investigator runs outside the request path. For the demo, the server creates a synthetic case, scopes it to specific integrations, versions and time windows, and makes three reads by default: lookup and order metrics, confirmation errors, and deployment history. The investigator receives those aggregates. The application retains authority over balances.
The local baseline uses deterministic rules. The optional Amazon Bedrock Converse adapter gets the same alert and facts. The model is asked to select one of two predefined hypotheses and return the source references and values that support it.[5]
Here is what BedrockAdapter actually asks the model. Along with choosing one of two hypotheses, it must cite records that an engineer can compare across windows and integrations.
String prompt = "Assess this synthetic alert: " + alert + ". Sources: " + json.writeValueAsString(facts) + ". Return one JSON object with hypothesis (CONFIRMATION_REGRESSION or" + " INTEGRATION_GAP) and evidence (map of exact source references to integer values)." + " Cite comparative windows and integrations."; An evaluator looks up every cited value and checks whether the matching references, taken together, support the chosen hypothesis. The program then adds the alternative explanation, missing information and next check defined for that hypothesis. An engineer reviews the resulting report. [12]

Figure 4. The reader gathers three sources, the investigator proposes a hypothesis, and the evaluator checks its support before human review. The Bedrock path was exercised with scripted responses.
Two findings that send the on-call engineer to different places
After deployment, Alpha and Beta each recorded 16 errors and zero orders per window on v2. For example, health/alpha/v2/600/confirmationErrors is 16. A confirmation regression fits, but a downstream outage could have coincided with the rollout. The next check is dependency health and confirmation traces before and after a rollback.
In the concentrated case, metrics/alpha/v1/1200/orders is 0 while metrics/beta/v1/1200/orders is 16. Alpha recorded no confirmation errors. Did its client ever attempt confirmation? Client telemetry can distinguish an interruption from an intentional lookup-only workflow. The data leaves intent unresolved. [10]
An AI agent can also be the client making the lookups. A sequence of authorized reads can still expose personal data. The purpose of the lookup and the fields the server returns matter well beyond payments. [3]
The same question at a retail support desk
A support agent needs a delivery date. If opening the order also reveals the customer’s phone number, full address, and purchase history, a routine question exposes far more than the task requires.
What did the support ticket authorize?
Risk: genuine details about a purchase can make a social engineering message more convincing. Brazil’s federal government has documented scams that use real personal details. [6]
Control: verify on the server that the ticket, order, and agent belong together. Return the delivery date for a delivery-date question. Audit the category of data accessed without copying the phone number into the log.
Imagine two comparable shifts, each with 100 reads. One has 5 reads without a linked ticket, the other has 40. Before drawing a conclusion about either team, I would check assignment patterns and whether the integration recorded the link.
Figure 5. At the same total volume, unlinked reads rose from 5 to 40 in this fictional support example.
What we measured locally
The Java application makes the admission decision inline. Investigation runs separately on events with opaque IDs. The report deduplicates events and attributes each payment to the original lookup window.
Choose the denominator before raising an alert
Eight found keys and two missing keys give ten conclusive results. One additional timeout counts as a technical error. The missing-key fraction is 2/10, or 20%.
Eleven admitted lookups and four orders give 2.75 lookups per order. With zero orders, the report shows both counts and leaves the ratio undefined.
The default window is ten minutes, with two more minutes for the payment to arrive. A window needs at least 12 admissions to qualify for interpretation.[10]
For deterministic triage, all 16 cited values matched their sources in the deployment case, as did all 14 in the Alpha case. The scripted adapter returned 12 of 12 and 7 of 7 matching references, respectively. The evaluator recorded zero unsupported claims across the four outputs. [10]
What happens if the investigator cites the right record but gives the wrong number? Triage checks each reference and value against the case. Only matching pairs count toward support for the hypothesis.
var correct = new HashMap<String, Integer>(); evidence.forEach( (key, n) -> { if (n != null && n.equals(facts.get(key))) correct.put(key, n); }); boolean supported = supports(hypothesis, correct); These counts measure citation fidelity on two synthetic cases. A live model’s usefulness on unfamiliar incidents, its latency and its cost remain open questions.
What I would measure on AWS
Amazon API Gateway: run a burst through gateway throttling and record which rejections came from the gateway and which came from the application’s per-identity rule. [4]
Amazon ElastiCache: repeat the last-token and receipt checks during a node failover. Compare the resulting balance, receipts, and directory read count.
End-to-end latency: measure lookup latency under realistic concurrency. For live Bedrock triage, separately measure response time, cost per investigation, and the fraction of claims supported by the cited evidence.
Reproduce the local result
With Java 25 and Docker running, start in the repository root. The first command runs the three test suites and the two synthetic investigations with a simulated Bedrock transport. The second starts the demo replicas on ports 8081 and 8082. [11]
sh gradlew clean build report investigate -Pmode=simulated
docker compose -f config/compose.yaml up -d --build
The recorded build passed 8 unit, 3 integration, and 4 component tests. The README walks through a lookup on one replica and POST /payment-orders on the other, including retries with the original idempotency key. [10] [11]
The question I take into architecture reviews
If lookups were still returning in a few milliseconds tomorrow, but payments stopped happening, which indicator would get your team’s attention?
Working on Pix taught me to look for that answer in the events that follow an HTTP 200.
References
[1] Banco Central do Brasil. DICT Operating Manual, v8.5, section 13 (Portuguese).
[2] Bucket4j. Java rate limiting and distributed backends.
[3] OWASP. Unrestricted Access to Sensitive Business Flows.
[4] AWS. Throttle requests to your REST APIs in API Gateway.
[5] AWS. Amazon Bedrock Runtime Converse command reference.
[6] Brazilian federal government. Advisory on impersonation using personal data (Portuguese).
[7] Proof of concept. Acceptance criteria and implementation tasks.
[8] Proof of concept. LastTokenTest, the concurrent admission test.
[9] Proof of concept. RecoveryTest, duplicate delivery and restart reconciliation.
[10] Proof of concept. Recorded test and Docker Compose results (Portuguese).
[11] Proof of concept. Run the experiments with Gradle and Docker Compose.
[12] Proof of concept. Java case reader, investigator, Converse adapter and hypothesis evaluator.
