A database is a collection of structured data that is stored in a computer system, and it can be hosted on-premises or in the cloud. As databases are designed to enable easy access to data, our resources are compiled here for smooth browsing of everything you need to know from database management systems to database languages.
Post-Migration Modernization: When and How to Refactor
Relate, Jev, and MCP: A Judgment Ledger for Agent Decisions
Fraud rings are closed loops of payments: account A pays B, B pays C, and C pays A, usually for almost the same amount, and often within hours. Ordinary traffic produces loops by chance, so finding a loop is easy, and deciding whether it is a ring is the hard part. This article builds a small experiment around that question. We generate a synthetic payments dataset in Snowflake with a known set of rings and a deliberate set of decoys. We find every candidate loop with a SQL query that runs in the database. We then ask a hosted model (Jev from TypeSafe AI) to judge each loop twice: once with a bare question, and once with a guided question that explains what to look for. Finally, we score both answers against the hidden ground truth and compare them with two plain rules that use no model at all. The short answer: guidance matters a great deal, and a well-crafted rule is a strong contender. Read on for more details, including a few things that went wrong on the way. What We Are Building The project is two Jupyter notebooks that run on your own machine and connect to Snowflake remotely: The first notebook creates the ACCOUNTS and TRANSACTIONS tables, with planted rings and decoys.The second notebook finds candidate loops in SQL, asks the model to judge a sample of them and scores the answers. The flow for each run looks like this: The generator writes the data to Snowflake and reads it back to check it.The triage notebook runs a self-join query in Snowflake that returns every closed loop of three or four accounts, with its timing and amount ratio computed in the database.Each loop becomes a small record: the amounts, the minutes between transfers, the account risk scores and a few summary numbers. The record holds no account ids, customer names, transaction ids or fraud label.The model answers a bare question and a guided question for each loop in a sample.We score the answers against the IS_FRAUD_RING label, which the model never sees. The notebooks support three model modes: hosted (Jev over the internet), local (a model served by Ollama on your machine), and replay (answers saved from an earlier hosted run, so the notebook runs with no model access). All results in this article come from the hosted model. Prerequisites You'll need: Python and Jupyter on your machine, running in a virtual environment (venv).A Snowflake account and a role that can create a database and a warehouse. SYSADMIN works.Key-pair login set up for your Snowflake user (refer to the Gotchas section).A TypeSafe API key for hosted mode. Replay mode needs no key. Set the following environment variables before launching Jupyter: Shell export SNOWFLAKE_ACCOUNT="<your-account-identifier>" export SNOWFLAKE_USER="<your-user>" export SNOWFLAKE_PRIVATE_KEY_PATH="rsa_key.p8" export SNOWFLAKE_ROLE="SYSADMIN" export SNOWFLAKE_WAREHOUSE="FRAUD_RING_WH" export TYPESAFE_API_KEY="<your-api-key>" The database defaults to FRAUD_RING_DEMO and the schema to PUBLIC. Set SNOWFLAKE_DATABASE or SNOWFLAKE_SCHEMA to change them. If your key has a passphrase, set the SNOWFLAKE_PRIVATE_KEY_PASSPHRASE as well. Newer Snowflake accounts may block single-factor password login, so key-pair login is the safer choice. Creating the Key-Pair Generate a private key in PKCS8 format and derive the public key from it using OpenSSL: Shell openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8 -nocrypt openssl rsa -in rsa_key.p8 -pubout -out rsa_key.pub The first command writes the private key to rsa_key.p8, which is the file SNOWFLAKE_PRIVATE_KEY_PATH points to. Keep it secret and never commit it to the repository. If you would rather protect it with a passphrase, remove -nocrypt from the first command. OpenSSL will then prompt for a passphrase, and you must also set SNOWFLAKE_PRIVATE_KEY_PASSPHRASE. Registering the Public Key Print the public key body on one line, without the header and footer lines: Shell grep -v "PUBLIC KEY" rsa_key.pub | tr -d '\n' Copy that output. Paste only this key body into Snowflake, leaving out the -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- lines. Then set it on your user: SQL SET my_username = CURRENT_USER(); ALTER USER IDENTIFIER($my_username) SET RSA_PUBLIC_KEY='<your-public-key>'; To confirm the registration, check that the user now has a key fingerprint: SQL DESC USER IDENTIFIER($my_username); Look for a value in the RSA_PUBLIC_KEY_FP row. You may need to run ALTER USER as a role that can modify your user, such as SECURITYADMIN or ACCOUNTADMIN. The Two Snowflake Tables The generator creates two tables. Both are fully synthetic and the same seed always produces the same data: TableColumnsACCOUNTSACCOUNT_ID, CUSTOMER_NAME, RISK_SCORETRANSACTIONSTX_ID, SOURCE_ACCOUNT_ID, TARGET_ACCOUNT_ID, AMOUNT, TIMESTAMP, DESCRIPTION, IS_FRAUD_RING TIMESTAMP is a real TIMESTAMP_NTZ, and IS_FRAUD_RING is the text 'True' or 'False'. Every transfer that belongs to a real ring is flagged there, which gives us the ground truth. The default dataset has 1,000 accounts and 50,000 background transactions, which are random transfers between random accounts. The loops are added on top. The first dataset ends up with 50,271 transactions, 191 of them real-ring transfers in 45 real rings. Transaction IDs are assigned after everything is shuffled together, so an ID says nothing about whether a transfer belongs to a ring. Each loop uses its own accounts, and no account appears in two loops. The Rings and the Decoys An easy dataset would not teach us much. In our first version, the guided question and a simple timing rule both scored 100 percent, which told us the data was too easy. So the generator plants five kinds of loops: KindCountTimingAmountsAccount RiskReal Ring?ring33Minutes apartWithin about 3%0.35 to 0.95Yeslookalike10Minutes apartWithin about 3%0.05 to 0.55Nouneven_fast10Minutes apartAt least 10% apart0.01 to 0.99Noslow_ring6One to three days apartWithin about 3%0.35 to 0.95Yesuneven_ring6Minutes apartAbout 4% to 14% apart0.60 to 0.95Yes The kinds are chosen so that no single signal separates rings from decoys: A timing rule finds the fast, near-equal rings but also the look-alikes, and it misses the slow rings.Equal amounts alone catch the look-alikes too.Risk scores overlap between real rings and look-alikes in the 0.35 to 0.55 band.A tight amount cut-off misses the moderately uneven real rings. The hard cases are on by default. In the data generator notebook, set INCLUDE_HARD_CASES = False to get only the real rings. Finding Candidate Loops in SQL The triage notebook does not ask the model to find loops. Snowflake does that with a self-join on the transactions table. For three-account loops, the query looks like the following, trimmed for space: SQL WITH in_window AS ( SELECT tx_id, source_account_id, target_account_id, amount, timestamp, is_fraud_ring FROM FRAUD_RING_DEMO.PUBLIC.TRANSACTIONS WHERE amount > 3000.0 AND amount < 10000.0 ) SELECT t1.tx_id, t2.tx_id, t3.tx_id, ... FROM in_window t1 JOIN in_window t2 ON t1.target_account_id = t2.source_account_id JOIN in_window t3 ON t2.target_account_id = t3.source_account_id WHERE t3.target_account_id = t1.source_account_id AND t1.source_account_id < t2.source_account_id AND t1.source_account_id < t3.source_account_id AND t2.source_account_id <> t3.source_account_id The query starts each loop at its lowest account ID, so it finds every loop once. The outer query adds the span in hours, the ratio of the largest to the smallest amount, and a flag for whether every leg is labeled as fraud. That flag is the ground truth, and it is never sent to the model. By default, the notebook searches for rings of three and four accounts. The search takes under a second on an X-Small warehouse. Larger rings can produce tens of thousands of candidates, so the MAX_AMOUNT_RATIO keeps the search small if you raise HOPS_MAX. On the first dataset, the search returns 861 candidates: 165 three-account loops and 696 four-account loops. Only 24 of them (2.8 percent) are real rings. The rest are chance loops and decoys. What the Model Sees Each loop becomes a small record. The following shows one of the sampled loops: JSON { "context": "A closed cycle of money transfers between bank accounts: each account pays the next one, and the last pays the first.", "accounts_in_cycle": 4, "transfers": [ {"hop": 1, "amount": 9627.21, "minutes_after_first_transfer": 89}, {"hop": 2, "amount": 9681.66, "minutes_after_first_transfer": 155}, {"hop": 3, "amount": 9733.96, "minutes_after_first_transfer": 244}, {"hop": 4, "amount": 9724.9, "minutes_after_first_transfer": 0} ], "account_risk_scores": [0.59, 0.62, 0.58, 0.68], "average_account_risk": 0.62, "total_span_hours": 4.07, "largest_to_smallest_amount_ratio": 1.011 } In hosted mode, this record is what leaves your machine. It holds amounts, minutes between transfers, risk scores, and the account count. It does not hold account IDs, customer names, transaction IDs, or the fraud label. The Questions We ask three questions. The first two are choices, and the third is a score. The bare question gives the model the record and asks whether it looks like a deliberate money-laundering ring or a coincidental cycle, with no hint about what separates them. The model can answer likely_ring, coincidental_cycle, or needs_review. The guided question asks the same thing, but tells the model what to weigh. It gives rough bands for the amount ratio and the average risk and says that timing is only a hint: Python GUIDED_QUESTION = Choice( instructions=( "Does this cycle of transfers look like a deliberate money-laundering ring, or a coincidental cycle " "in ordinary traffic? Judge it on amounts and risk together.\n" "Amounts: largest_to_smallest_amount_ratio up to about 1.03 is near-equal. Up to about 1.15 is moderately " "uneven. Above about 1.15 is clearly uneven, and then it is not a ring whatever the risk says.\n" "Risk: average_account_risk above 0.45 is high, below 0.35 is low, and between 0.35 and 0.45 is middling.\n" "Decide like this. Amounts up to about 1.15 and high risk: a ring. Near-equal amounts and low risk: a " "legitimate cycle. Only a middling average risk: needs review.\n" "Timing is only a hint. Many rings finish within hours, but some take days between transfers, so a long " "span alone does not rule a ring out." ), criteria={ ... }, ) The urgency score asks how soon an investigator should look at a loop using the same bands. The notebook ranks loops by this, but this article does not evaluate that ranking. The Baselines A model call is only worth it if the call beats a rule, or does something a rule cannot. We compare against two rules that use no model: The timing rule flags a loop when its span is within 24 hours, and its amount ratio is within 1.032.The amounts and risk rule ignores timing, flags a loop when its amount ratio is within 1.032, and its average account risk is at least 0.5. The second rule is deliberately strong. We added it after seeing that the data was separable on those two features. The model is compared against the best simple alternative, not against a weak one. The Sample We do not send all 861 candidates to the model. The notebook sends a sample of 100 loops, built in three steps: Send all the real rings, up to half the sample.Send the most tricky non-rings, which are loops that finish within the rule's time window without being real rings. These take up to 30 percent of the sample.Send a random draw from everything else. The second step matters more than it looks. When we first sampled the non-rings at random, the timing rule scored a perfect 1.0 on the sample, and 0.68 on all candidates. The look-alike decoys seldom landed in the sample. Reserving part of the sample for fast non-rings fixed that. The rules now score the same on the sample as on the full population. So the sample represents the difficulty. The sample for the first dataset held all of the 24 real rings and 12 fast non-rings. Running the Notebooks Run the generator first. It connects, creates the database and warehouse if they are missing, and then: Checks that the two tables do not already exist,Generates the data,Loads it with write_pandas, Reads it back and compares row counts, the number of real-ring transfers, the sum of the amounts, and the earliest and latest timestamps. You should see: Plain Text FRAUD_RING_DEMO.PUBLIC is ready: 50,271 transactions, 191 of them in 45 real rings. Then run the triage notebook. Set MODE to hosted, local or replay in section 3. A 100-loop sample takes a few seconds per question with the hosted model. At the end of the run, the notebook can save the hosted answers to a replay file. You can rerun the whole comparison later with no model access. To rerun a notebook against existing tables, note that the generator will stop with a plain message and change nothing. To replace them, set REPLACE_TABLES_IN to the exact target, for example "FRAUD_RING_DEMO.PUBLIC", and run again. The notebook lists the tables with their row counts and confirms the role can create tables before it replaces anything. Set the variable back to None afterwards. The Held-Out Dataset The guidance contains numbers, such as 1.15 and 0.45, which we chose after looking at the first dataset. That raises an obvious question: does the guidance work only because it was tailored to this data? To test that, each notebook has a HELDOUT switch. In the generator, HELDOUT = True builds a second dataset with a different seed and shifted ranges. Real-ring risk drops to 0.30 to 0.90, look-alike risk rises to 0.10 to 0.60, and the moderately uneven rings are slightly more uneven. The data is written to its own schema (HELDOUT) so the first dataset stays in place. In the triage notebook, HELDOUT = True reads from that schema and keeps a separate replay file. The guidance is not retuned. The second dataset has 50,267 transactions, 186 real-ring transfers and 854 candidate loops (of which 27 are real rings). Results on the First Dataset The following table displays the results on the 100-loop sample. A loop counts as flagged when the answer is likely_ring: MethodFlaggedReal Rings CaughtFalse AlarmsPrecisionRecallBare question3723 of 24140.6220.958Guided question2523 of 2420.9200.958Timing rule2517 of 2480.6800.708Amounts and risk rule1919 of 2401.0000.792 The bare question method finds 23 of the 24 real rings, but pay for it with 14 false alarms (compared to 2 for the guided question). The guided question catches four more real rings than the amounts and risk rule, at the cost of two false alarms. It also finds the slow rings and the moderately uneven rings that the other rules miss. This is because the guidance tells it that timing is only a hint, and that moderately uneven amounts can still be a ring. The timing rule is the weakest. It misses seven real rings and raises eight false alarms. There is one more comparison worth looking at. If every needs_review answer goes to a person: MethodLoops Sent to a PersonReal Rings ReachedFalse AlarmsGuided question, flagged or sent to review2924 of 245Amounts and risk rule1919 of 240 The guided question reaches all 24 real rings, and a person opens 29 loops to do it. The amounts and risk rule reaches 19 of 24 from 19 loops. Whether the extra ten loops are worth the five extra rings depends on what a missed ring costs. Results on the Held-Out Dataset Here is the same notebook run against the held-out schema, with no change to the guidance: MethodFlaggedReal Rings CaughtFalse AlarmsPrecisionRecallBare question3324 of 2790.7270.889Guided question2826 of 2720.9290.963Timing rule2519 of 2760.7600.704Amounts and risk rule2322 of 2710.9570.815 The shape of the result is the same. The guided question lands at 0.929 precision and 0.963 recall, against 0.920 and 0.958 for the first dataset. It catches four more real rings than the amounts and risk rule, against one more false alarm. Sent for review, the guided question reaches all 27 real rings from 31 loops, while the amounts and risk rule catches 22 of 27 from 23 flagged. What Went Wrong on the Way The guidance went through several versions, and the numbers show why we did not stop at the first one. The samples differ between rows, so read the table as indicative: GuidanceGuided PrecisionGuided RecallWhat HappenedTiming-based: a span over a day is a coincidence0.9440.850Missed every slow ring. Matched the timing rule.Amounts and risk, in words0.9470.900Better, but flagged a loop with a ratio of 1.20.Bands, with "high risk" meaning scores mostly above 0.61.0000.333Over-cautious. Sent 16 of 24 real rings to review.Bands on the average risk, with 0.45 as high0.9200.958The final version. The third row is the instructive one. The model followed our bands faithfully, and the bands were wrong. Our real rings start at a risk of 0.35, so a threshold of 0.6 put most of them in the middling band, and the model compliantly sent them to review. The fix was twofold. We added an average_account_risk field to each record (so the model does not have to do the arithmetic), and we put the high threshold at 0.45, where the data actually separate. A language model applies the thresholds you give it literally. If they are wrong, the answers will be wrong consistently and decisively. Conclusions On two synthetic datasets, built with different seeds and different risk ranges, we found the following: Guidance is worth more than the model alone. The same model, asked the same question with and without guidance, cuts false alarms from 14 to 2 on the first dataset and from 9 to 2 on the second, at equal or better recall.The guided model beats the best simple rule on recall. It catches four more real rings than the amounts and risk rule on both datasets, including the slow and moderately uneven rings that a tight cut-off cannot find.The rule keeps the edge on precision. With zero or one false alarm, the amounts and risk rule is the more precise method, and it needs no model.A mixed answer is useful. Counting needs_review as an escalation, the guided question reaches every real ring on both datasets, which a rule with a cut-off cannot do.The sample should reflect the difficulty. A random sample of non-rings hides the decoys and flatters the rules. Caveats Synthetic data. The data have the structure we gave them. These results show that guidance carries across draws of the same generator, not that it works on real transactions.Small samples. Each run has 24 to 27 real rings, so a difference of a loop or two is noise. The model's answers can also shift a little between runs: the bare question gave 22, and then 23 real rings were caught on the same data.The guidance is tuned to the data. The bands encode the generator's ranges. The held-out test shows they survive a shift, but it was modest, and we did not retune.Only the hosted model was measured. The local mode (which uses a small Ollama model) exists in the notebook, but we did not run its results here.The urgency score is unevaluated. The notebook ranks loops by it, but we did not assess the ranking.A rule can be strict. Two features and two thresholds got within a few false alarms of the model, so a rule is the baseline to beat, not a strawman.One search window. The query finds only loops with transfers between 3,000 and 10,000, and three or four accounts. Rings outside that window are not candidates. Gotchas These cost us the most time, and they are worth knowing about before you run the notebooks: Password login can be blocked. Newer Snowflake accounts reject single-factor password login with an "incorrect username or password" error even when the password is right. Set up key-pair login and set SNOWFLAKE_PRIVATE_KEY_PATH. A relative path works if the key file sits next to the notebook.The role that creates the database owns it. Objects created by ACCOUNTADMIN are not usable by SYSADMIN. Use one role (such as SYSADMIN) for both notebooks, and a new database name, rather than a pre-existing database owned by another role.Replacing tables is guarded. The generator never drops a table by default. REPLACE_TABLES_IN must match the target exactly, and the notebook checks that the role can create tables before it replaces anything. We added this after an earlier version dropped tables before discovering it lacked the privilege to recreate them.Timestamp parsing. TRY_TO_TIMESTAMP_NTZ accepts text only. The triage query wraps the column in TO_VARCHAR so it works whether the column is text or a real timestamp.Replay files are tied to the question and the sample. They are keyed by loop and question, so if you change the guidance or the sample, the saved answers are stale. Delete the replay file and record a new one. Each dataset has its own replay file, so the two datasets do not clash.Stops are quiet. When a notebook stops deliberately (e.g., because the tables already exist), it prints a message instead of an error warning. Real failures, such as missing privileges, still raise errors.Leave REPLACE_TABLES_IN as None. Set it only for the run that needs it, then set it back. Summary We built a small Snowflake experiment around one question: when you ask a model whether a loop of payments is a fraud ring, how much would it help to tell the model what to look for? On a synthetic dataset with decoys and hard cases, the bare question caught nearly every real ring but raised 14 false alarms. The guided question kept the recall and cut the false alarms to 2. On a second dataset, with a different seed and shifted ranges, the same guidance gave 0.929 precision and 0.963 recall. A well-chosen rule is a serious competitor. The amounts and risk rule was the most precise method on both datasets, and the guided model beat it only on recall and its ability to send mixed cases to a person. The model's value here is not that it replaces a rule. It's that it handles the cases cut-off rules miss, once you tell it what matters. The practical lesson is to treat the guidance as part of the system. Test it on a dataset you did not tune it on. Check that the sample shows the hard cases. Read the thresholds as carefully as the code. A missed ring and a needless review do not cost the same, and the right method depends on which one you can afford. The full source code is available on GitHub.
An event payload is an API, even if nobody on the team calls it one. The moment an order.created message lands on a Kafka topic, and three other services start reading it, that payload has consumers, a contract, and a long memory. Change it carelessly and something downstream breaks, often hours later, often in a service whose owners didn’t know the event had changed at all. Most API regression testing practice grew up around HTTP. Send a request, compare the response to a baseline, flag the difference. Async APIs don’t fit that shape neatly. There’s no response to compare; the consumer might process the message much later, and the breaking change might not even be in the schema. Teams that run heavily event-driven architectures tend to learn this the hard way, so it’s worth looking at what API regression testing needs to cover when the API is a stream of messages. Why Async APIs Break Differently With an HTTP API, a regression usually shows up quickly. A client calls an endpoint, gets an unexpected response, and fails right there. Events loosen that feedback loop in a few ways. Producers and consumers deploy independently, so a producer change can sit on a topic for days before an older consumer version reads it. Consumers often process messages asynchronously, so failures surface as stuck consumer groups, dead-letter queues, or quietly wrong data rather than clean errors. And a single topic frequently has consumers the producing team has never heard of, like an analytics pipeline, a search indexer, or a team’s experimental service. The result is that event regressions tend to be discovered late and far from their cause. That’s exactly the situation regression testing is supposed to prevent. What Schema Compatibility Checks Catch The first line of defense for many teams is a schema registry. Confluent Schema Registry, for example, lets each subject enforce a compatibility mode. Backward compatibility means consumers using the new schema can still read data written with the previous one. Forward compatibility means consumers still on the old schema can read data written with the new one. Full compatibility requires both. There are transitive variants that check against all previous versions, not just the latest. These checks are genuinely valuable. Try registering a schema that drops a field consumers still read, or swaps a type for something incompatible, and the registry simply refuses, so the bad version never reaches the topic. For Avro and Protobuf payloads especially, that catches a big chunk of structural breakage without anyone having to remember to look. Teams using plain JSON without a registry don’t get this enforcement at all, which is one reason JSON event payloads tend to drift more than schema-managed ones. AsyncAPI specifications can document the contract, but documentation alone doesn’t stop a breaking change from shipping. What Schema Checks Miss Here’s where API regression testing has to go further. A schema describes structure. A lot of real event regressions are about meaning, and those sail straight through compatibility checks. A field called amount switches from cents to dollars. Same name, same type, fully compatible schema, and every consumer that sums amounts is now off by a factor of a hundred. A status enum gains a new value that older consumers don’t handle, so their switch statements fall through to a default branch nobody tested. A timestamp moves from UTC to local time. An optional field that was always populated in practice starts arriving empty because of an upstream refactor. Some regressions aren’t even in the payload. Take the message key. Change it, and in Kafka the events start landing on different partitions, so the per-key ordering consumers counted on quietly goes away. Or a retry tweak ends up producing more duplicates than before, and suddenly it matters whether consumers were actually idempotent or just never tested for it. A refactor starts emitting two events where there used to be one. None of these show up as schema violations. They show up as wrong numbers in a dashboard, or a customer charged twice. Using Real Messages as the Regression Baseline So how do you catch problems the schema can’t see? The same way HTTP regression testing does, really. You keep a picture of what known-good behavior looked like, and every change gets compared against it. In an event-driven system, that picture comes from real message traffic. Start with producers. Grab the inputs that make a service publish something, plus whatever it actually published in response. Once someone changes the service, feed it those same inputs again and line up its new messages against the old ones. Amounts in different units, an enum value nobody’s seen before, a different key, an event that wasn’t there last time: it all pops out as a difference, and a “compatible” schema doesn’t hide any of it. On the consumer side, it works in reverse. Recorded messages from the real topic get replayed into the new consumer version, and the test checks what the consumer does with them: the database writes it makes, the downstream calls it sends, the events it publishes in turn. A consumer that suddenly mishandles a message it processed fine last week gets caught before deploy rather than in production. Recording at the network level makes this considerably easier, since application code doesn’t need instrumenting to capture broker traffic. Keploy, an open-source tool, takes this approach, capturing Kafka and RabbitMQ traffic alongside HTTP calls and database queries and replaying the recorded interactions as mocks, which lets a service’s event behavior be checked in CI without a live broker. The Tradeoffs Worth Knowing About Message-based regression baselines are powerful, but they come with real costs, and teams adopting them tend to run into the same few. Noise is louder than in HTTP. Event payloads are full of values that differ every run: event IDs, timestamps, correlation IDs, sometimes broker metadata like offsets. Without careful field-level ignore rules, every comparison looks like a regression. What tends to save teams is being stingy with those rules. Ignore one specific field at a time, never a whole payload, and leave a short note on each rule explaining why it’s there, because six months later nobody will remember.Ordering often isn’t stable. Say a service fires off a few events at once. They might show up in one order today and a different one tomorrow, and that’s not a bug. So the comparison has to know where order genuinely matters, like within one key’s stream, and where it’s fine to shrug.Payloads often carry sensitive data. Real events frequently include customer details. Recording from production, or from staging copies of production data, means redacting before anything is stored, and redacting to stable placeholder values so relationships between events survive.Volume needs sampling. High-throughput topics produce far more messages than a regression suite needs. Teams typically sample by event type and by edge case, aiming for coverage of distinct behaviors rather than raw volume.Baselines age. An intentional change to an event means re-recording, and that update deserves the same review as the code change. Otherwise “intended” quietly becomes “whatever the last recording said.” Where Contract Tests Fit In Consumer-driven contract testing covers some of the same ground from a different angle. Pact is a good example. With its message pacts, each consumer writes down the message shape it’s expecting, and the producer’s build checks that it can still produce exactly that. When teams can coordinate like this, it works well, and getting consumer expectations written down is worth a lot. Contract tests and recorded baselines tend to complement each other. Contracts capture what consumers say they need. Recorded traffic captures what actually flows through the system, including the unofficial consumers and undocumented fields that contracts never mention. Teams with many independent consumers often find the second category is where the surprises live. A Practical Layering Pulling this together, event-driven API regression testing usually ends up layered. Schema compatibility checks in the registry block structurally breaking changes at publish time. Contract tests make known consumer expectations explicit. Recorded message baselines, replayed in CI against new producer and consumer versions, catch the semantic and behavioral changes the other two layers can’t see. And in production, monitoring dead-letter queues and consumer lag gives an early warning when something still slips through. No single layer covers everything, and that’s the point. Each one catches a different kind of regression at a different cost. Conclusion Event-driven systems don’t remove API contracts. They just make them easier to forget, because nobody calls an endpoint and nobody gets an immediate error. Schema registries handle structural safety well, but the regressions that hurt most in async systems are usually about meaning: units, enums, keys, ordering, and duplicates. API regression testing for async APIs has to compare behavior, not just shapes. The topics most worth protecting first are the ones with the most consumers and the least visibility into who those consumers are. Those are where a compatible-looking change is most likely to break something nobody was watching.
If you've ever reached for SQLite to answer a question about a CSV, you already know the appeal: no server, one file, connect() and go. Relate (formerly CypherLite), a Neo4j project, brings that experience to graph data. It's an embedded graph database written in Rust, queried in Cypher, and runs inside your Python process. This article uses it in a notebook on a dataset that is naturally a graph, the London Underground. We'll load stations and connections, ask questions that would need self-joins in SQL, such as: What's within three stops?Which stations are interchanges?How do I get from A to B? and hand the results to pandas. The SQLite parallels are close. The database is a single .cl file or lives in memory. The Python API is connect() and execute() with named parameters, and rows come back keyed by column name. There is no daemon to start and no connection string. The full source code is available on GitHub. Install And Run A First Query The package is called relate-db on PyPI and imported as relate. Relate ships prebuilt wheels for Windows, Linux, and macOS, so there's nothing to compile. It needs Python 3.9 or later; the pinned package versions in the accompanying notebook need Python 3.11 or later. If you've used sqlite3, the first query will look familiar: Python db = relate.connect(":memory:") # or a path such as "tube.cl" db.execute("CREATE (:Station {name: $name})", {"name": "Kennington"}) for row in db.execute("MATCH (s:Station) RETURN s.name AS name"): print(row["name"]) execute() takes the query and a dictionary of parameters, and each row is addressable by column name. Use parameters rather than string formatting, for the same reason you would in SQL. Load The London Underground Data The dataset is three CSV files: Stations with coordinatesConnections between neighboring stations with the line that serves themA list of lines The connections file also holds other London rail lines, so the code keeps only the lines in the lines file. We'll read the files with pandas and pass the rows as a parameter. UNWIND turns the list into one row per record, similar to executemany in SQLite. Python stations = pd.read_csv("data/london_stations.csv") links = pd.read_csv("data/london_connections.csv") lines = pd.read_csv("data/london_lines.csv") for frame in (stations, links, lines): frame.columns = frame.columns.str.strip() # Keep the lines in the lines file, and only the stations those lines touch. links = links[links["Tube Line"].str.strip().isin(set(lines["Tube Line"].str.strip()))] used = set(links["From Station"].str.strip()) | set(links["To Station"].str.strip()) stations = stations[stations["Station"].str.strip().isin(used)] db = relate.connect("tube.cl") db.execute( "UNWIND $rows AS r " "MERGE (s:Station {name: r.name}) " "SET s.lat = r.lat, s.lon = r.lon", {"rows": [ {"name": str(r["Station"]).strip(), "lat": float(r["Latitude"]), "lon": float(r["Longitude"])} for r in stations.to_dict("records") ]}, ) db.execute( "UNWIND $rows AS r " "MATCH (a:Station {name: r.a}), (b:Station {name: r.b}) " "CREATE (a)-[:CONNECTS_TO {line: r.line}]->(b)", {"rows": [ {"a": str(r["From Station"]).strip(), "b": str(r["To Station"]).strip(), "line": str(r["Tube Line"]).strip()} for r in links.to_dict("records") ]}, ) Each connection is stored once. The queries below match it in either direction, so a trip works both ways without storing every link twice. Cypher also has LOAD CSV, which skips pandas. Relate denies local file reads unless we allow a directory explicitly, so the parameter route is the simpler approach in a notebook. We'll check the load with a count: Python print(db.execute("MATCH (s:Station) RETURN count(s) AS stations").data()) print(db.execute("MATCH ()-[r:CONNECTS_TO]->() RETURN count(r) AS links").data()) On the Underground data, this outputs 349 stations and 458 connections. Ask Graph Questions Three questions that need self-joins in SQL read as one pattern in Cypher. 1. What's Within Three Stops Of Kennington? A variable-length pattern follows connections up to a limit, in either direction: Python nearby = db.execute( "MATCH p = (a:Station {name: $name})-[:CONNECTS_TO*1..3]-(b:Station) " "WHERE a <> b " "RETURN b.name AS station, min(length(p)) AS stops " "ORDER BY stops, station", {"name": "Kennington"}, ).data() Kennington has 4 neighbors, 8 more stations two stops away and 12 more at three stops, 24 in all. 2. Which Stations Are Interchanges? Group each station's connections by line and keep the ones served by more than one: Python hubs = db.execute( "MATCH (s:Station)-[r:CONNECTS_TO]-() " "WITH s, collect(DISTINCT r.line) AS lines " "WHERE size(lines) > 1 " "RETURN s.name AS station, size(lines) AS lines, lines AS served_by " "ORDER BY lines DESC, station LIMIT 10" ).data() Kings Cross St. Pancras comes first with 6 lines, followed by Baker Street with 5. 3. How Do I Get From Kennington To Euston? Cypher 25 path selectors ask for the shortest paths directly. Two details matter: Bound the search with a hop limit, because an open-ended pattern makes the engine consider every path through a network full of loops.Name the line if you want one, as below. Python ORIGIN, DEST, LINE = "Kennington", "Euston", "Northern" MAX_HOPS = 10 # the shortest route is 8 hops; the bound keeps the search small found = db.execute( f"MATCH p = SHORTEST 3 (a:Station {{name: $origin})-[:CONNECTS_TO {{line: $line}]-{{1,{MAX_HOPS}}(b:Station {{name: $dest}) " "RETURN [n IN nodes(p) | n.name] AS stations, length(p) AS stops ORDER BY stops", {"origin": ORIGIN, "dest": DEST, "line": LINE}, ).data() # Keep each station sequence once. routes = list({tuple(r["stations"]): r for r in found}.values()) On the Northern Line, the query returns the two branches in a few milliseconds: Charing Cross (8 stops, via Waterloo and Embankment)Bank (9 stops, via Elephant and Castle and Angel) Where several lines serve the same stations, the graph holds parallel connections, and each counts as a separate path, so the same station sequence can come back more than once. We'll keep each sequence once. Drop the line filter and the same question runs across the whole network. We ask for more paths than we need, keep the distinct station sequences, and return the line on each hop, so we can see where the route changes: Python whole = db.execute( f"MATCH p = SHORTEST 20 (a:Station {{name: $origin})-[:CONNECTS_TO]-{{1,{MAX_HOPS}}(b:Station {{name: $dest}) " "RETURN [n IN nodes(p) | n.name] AS stations, [r IN relationships(p) | r.line] AS lines, length(p) AS stops " "ORDER BY stops", {"origin": ORIGIN, "dest": DEST}, ).data() distinct = list({tuple(r["stations"]): r for r in whole}.values()) This takes under a second and returns 20 paths, but only two distinct routes, because most paths differ only in which parallel connection they use. The shortest has 6 stops: Northern Line to Waterloo, Jubilee Line to Green Park, then the Victoria Line through Oxford Circus and Warren Street to Euston, with two interchanges. The other has 7 stops through Bank, Moorgate and Farringdon, using the Northern, Waterloo and City, and Circle or Metropolitan Lines. Fewer stops does not mean a better trip, which is why a route's interchanges belong in the comparison. In SQL, the same three questions require recursive CTEs or repeated self-joins. Move Results Into Pandas Every query above returns a list of dictionaries through .data(), which pandas takes directly: Python hubs_df = pd.DataFrame(hubs) hubs_df.plot.barh(x="station", y="lines", legend=False).invert_yaxis() For larger results, the native Database class can return Arrow IPC bytes, which avoids building Python objects row by row. It needs the file to be free, so we'll close the earlier connection first: Python db.close() # the file must be free for the native class adb = Database("tube.cl") buf = adb.execute_arrow("MATCH (s:Station) RETURN s.name AS name, s.lat AS lat, s.lon AS lon") stations_df = pa.ipc.open_stream(buf).read_all().to_pandas() adb.close() From here, the data is an ordinary DataFrame. We can plot it, merge it with other tables, or feed it to a model, and write findings back with a parameterized UNWIND when we want them in the graph. Keep It In One File A path ending in .cl stores the write-ahead log, the snapshots and the catalog in a single file, so the whole graph can be copied, emailed or committed alongside the notebook. A plain directory path works too, and ":memory:" gives us a throwaway database that disappears when the process ends. Python db.close() db = relate.connect("tube.cl") # the graph is still there print(db.execute("MATCH (s:Station) RETURN count(s) AS stations").data()) Close a connection before another one opens the same file. Relate allows one writer, and a second opener of a locked database gets an error (an OperationalError, "storage locked"), as it would in SQLite. By default, a write is acknowledged after it reaches the log, so a crash does not lose it. Summary Relate fits analysis on a graph that lives on a local machine: a notebook, a script, a unit test for a Cypher query, or a prototype before being moved to a server. Because the dialect is Cypher, the queries carry over to Neo4j. Know the limits before you build on it: The working set must fit in RAMIt's an engine, not a platform: it has no equivalent of Neo4j's plugin ecosystem, such as Graph Data Science, and it does not let you register your own Cypher functionsIt's a subset of what Neo4j runs, so check each feature you depend on against the documentation, and test your queries on both engines before choosing For many applications, these trade-offs will be fine. We get a graph, a query language, and a DataFrame in one pip install, with nothing to run in the background. In the next article, we'll see how to use Relate with TypeSafe AI's Jev, LLMs and MCP. We'll build an AI agent that navigates the London Underground while recording its decisions, alternatives, model judgments, and human interventions in a persistent, queryable graph ledger. Stay tuned! The full source code is available on GitHub.
Retries usually make systems more reliable. A dependency times out, processing pauses, and the message returns later. Eventually, the operation succeeds. That successful retry can also corrupt a projection. Consider a consumer maintaining product data. Version 108 of product P17 starts processing but encounters an enrichment timeout. Version 109 arrives seconds later and reaches the database successfully. Five minutes afterward, version 108 returns through the retry queue and overwrites it. Both events are legitimate. Neither is a duplicate. The database accepts valid SQL, and the consumer reports success. Yet the stored state has moved backward. The missing guarantee is freshness. An idempotent consumer can prevent repeated execution of one operation while still allowing an older operation to replace newer state. Why Deduplication Cannot Catch This Suppose each product update carries a unique event identifier: Plain Text eventId=A, productId=P17, sourceVersion=108 eventId=B, productId=P17, sourceVersion=109 An idempotency check correctly treats these as different operations. Assuming failed attempts do not mark events complete, event A remains eligible for processing after its enrichment failure. Nothing about its identity tells the consumer that version 109 has already superseded it. Two separate questions must therefore be answered: Idempotency: Has this operation already been applied?Freshness: May this operation replace the state currently stored? For a projection governed by an authoritative revision, the required invariant is straightforward: the persisted version must never decrease. A replay can leave it unchanged, and a newer update can advance it. Event identifiers and source revisions serve different purposes. Preserving both avoids forcing one mechanism to provide a guarantee it cannot express. Reproduce the Failure at the Database Boundary The failure does not require a message broker. Two writes arriving in the wrong order are sufficient. Start with a small PostgreSQL table: SQL CREATE TABLE product_view ( product_id VARCHAR(64) PRIMARY KEY, source_version BIGINT NOT NULL, payload JSONB NOT NULL ); A conventional upsert accepts whichever update arrives last: SQL INSERT INTO product_view (product_id, source_version, payload) VALUES ('P17', 108, '{"name":"Keyboard","price":90}') ON CONFLICT (product_id) DO UPDATE SET source_version = EXCLUDED.source_version, payload = EXCLUDED.payload; If version 109 already exists, this statement replaces it with version 108. The database has followed the instruction exactly. The application never expressed a freshness constraint. This distinction matters during incident analysis. A retry queue explains why an event arrived late. The unconditional write explains why late arrival damaged state. Why Locks and Application Checks Fall Short A lock alone does not establish freshness. Version 109 can acquire the lock, write successfully, and release it. Version 108 can acquire that same lock later and overwrite the row. Processing was perfectly serialized, but the order was wrong. An application-level comparison introduces a different problem: Java Product current = repository.find(productId); if (incoming.version() > current.version()) { repository.save(incoming); } Starting from version 107, workers carrying 108 and 109 can both read the same row. Both comparisons pass. If the worker carrying 108 writes last, the projection regresses. The issue is the gap between comparison and mutation. A lock covering both operations can protect this sequence when implemented correctly, but the freshness comparison remains essential. For a single-row projection, putting the condition directly in the write makes the invariant explicit. Make the Write Enforce Freshness Add a version predicate to the conflict-update branch: SQL INSERT INTO product_view AS stored (product_id, source_version, payload) VALUES ('P17', 108, '{"name":"Keyboard","price":90}') ON CONFLICT (product_id) DO UPDATE SET source_version = EXCLUDED.source_version, payload = EXCLUDED.payload WHERE stored.source_version < EXCLUDED.source_version RETURNING product_id, source_version; PostgreSQL evaluates the conflict-update condition against the conflicting row. Rows excluded by that condition are not returned by RETURNING. See the PostgreSQL INSERT documentation. If 108 commits first, 109 can advance the row. If 109 commits first, 108 cannot replace it. Equal versions also leave the row unchanged. The comparison now occurs within the database operation that controls mutation. Concurrent processing no longer depends on the newest event finishing last. Transactions can still encounter deadlocks or serialization failures, depending on the workload and isolation level. Those failures require appropriate transaction retries; the version predicate must remain part of every attempt. PostgreSQL documents these distinctions in its transaction isolation guidance. Establish What the Version Actually Means The predicate is useful only when larger revisions represent newer authoritative state for the same entity. A source-owned aggregate revision is a strong candidate. A datastore revision or producer sequence can also work when its ordering contract is explicit. Random UUIDs establish identity without establishing order. Wall-clock timestamps require careful guarantees around clock synchronization, precision, and concurrent writers. Offsets from unrelated partitions do not provide a shared entity ordering. The payload must also correspond to its claimed revision. If enrichment reads changing external data, retrying version 109 might produce a different payload from the first attempt. The fence prevents replacement, but the inconsistency remains worth investigating. Define whether each event carries a complete snapshot or a dependent delta. Skipping revision 108 is safe only when 109 contains everything needed to represent the newer state. A sequence of incremental adjustments may require ordered processing or gap recovery. Distinguish Stale Updates From Conflicting Replays A rejected write has several possible meanings: incomig updateinterpretation Lower revision Stale delivery Equal revision, identical payload Replay Equal revision, different payload Consistency violation Higher revision Eligible replacement The SQL predicate protects the row but does not distinguish all these outcomes. If exact classification matters, compare against the protected row within a suitable transaction or retain revision-specific payload hashes. A later, unprotected read can observe a further update and obscure what happened during the original decision. Same-version conflicts can reveal nondeterministic enrichment, incorrect revision assignment, or corrupted replay data. Treating them as ordinary duplicates hides a broken data contract. Preserve Versions Across Deletion Physical deletion creates another opening for stale retries. Suppose version 121 deletes P17. If the row disappears entirely, a delayed version 120 encounters no conflict and inserts the product again. Preserve the deletion revision with a tombstone: SQL ALTER TABLE product_view ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE, ALTER COLUMN payload DROP NOT NULL; ALTER TABLE product_view ADD CONSTRAINT valid_payload_state CHECK ( (deleted AND payload IS NULL) OR (NOT deleted AND payload IS NOT NULL) ); Represent deletion as a versioned write carrying deleted = TRUE and a null payload. Use the same version predicate for active records and tombstones, updating both payload and deleted from the incoming row. A legitimate newer active revision must restore deleted = FALSE. Tombstone retention must cover retries, delayed delivery, backfills, and supported replay windows. Removing the tombstone removes the information needed to reject older revisions. Identifier reuse adds another complication. If revisions restart, compare an authoritative generation and revision together so generation 7, revision 1 can supersede generation 6, revision 982. Make Rejected Writes Operationally Useful A stale delivery should normally finish as a terminal no-op. Record the rejection and acknowledge the message. Retrying version 108 cannot make it newer than 109. Track applied updates, stale rejections, identical replays, and conflicting revisions separately. Include entity identifiers, incoming revisions, event identifiers, and delivery paths in diagnostic records. A sudden increase in stale rejections can expose a slow dependency, retry backlog, or unexpected replay. The fence protects correctness while those signals help explain the disruption. This approach fits snapshot projections with a meaningful authoritative order. Concurrent independent updates may instead require merge rules or field-level versions. The essential boundary is the write: once a newer revision is accepted, every later mutation must prove that it is allowed to advance that state.
Modern SaaS companies often rely on managed cloud services to build and scale their applications efficiently. While many start with a single cloud provider, expanding into new markets may create a need to support additional cloud environments, whether due to customer preferences or resilience requirements. However, this expansion can be challenging when applications are tightly coupled to services offered by their original cloud provider. DynamoDB in AWS is one example of this challenge. Applications built around its APIs may need to run against a different database backend in another cloud environment, and rewriting their data-access layer can require significant engineering effort. Applications that also rely on DynamoDB Streams to consume data changes face an additional challenge, as compatibility must extend beyond basic read and write operations. This article explores how providing DynamoDB-compatible APIs over Apache Phoenix/HBase addresses this problem. Specifically, it examines the design and implementation of DynamoDB Streams compatibility using Phoenix's change data capture capabilities. Apache HBase and Phoenix Apache HBase is an open-source, distributed NoSQL database built on top of the Hadoop ecosystem. It organizes data into tables that are partitioned into regions and distributed across multiple servers. Within each region, data is stored and accessed in sorted row-key order. As tables grow or their data distribution changes, HBase regions can split or merge, allowing the database to manage data across the cluster. Apache Phoenix provides a SQL interface over HBase, allowing applications to query and modify data using familiar SQL statements rather than working directly with the HBase APIs. It also provides capabilities such as secondary indexing and change data capture (CDC). Phoenix and HBase are widely available as part of enterprise big-data platforms, including Amazon EMR, Azure HDInsight, and Cloudera distributions. Apache Phoenix-Adapters Apache Phoenix Adapters is an open-source project that provides compatibility with Amazon DynamoDB APIs using Apache Phoenix and HBase as the underlying database. It is designed as a stateless HTTP service that translates DynamoDB API requests into operations supported by Phoenix. Applications can use Phoenix Adapters by simply changing their DynamoDB SDK endpoint to point to the service, without requiring changes to their application code. Amazon DynamoDB Streams Amazon DynamoDB is a fully managed NoSQL database service that supports key-value and document data models. DynamoDB Streams captures item-level changes to DynamoDB tables and makes them available for consumption by downstream applications. The DynamoDB Streams API provides four operations: ListStreams for discovering streams, DescribeStream for retrieving stream and shard metadata, GetShardIterator for obtaining a position within a shard, and GetRecords for reading change records. Together, these APIs allow applications to consume database changes through existing AWS SDKs and streaming tools. Apache Phoenix CDC and Stream Metadata Apache Phoenix supports Change Data Capture (CDC), allowing applications to query changes made to a table using SQL (PHOENIX-7001). The CDC implementation uses a write-optimized uncovered index on row timestamps to capture row-level modifications. The index tracks changes without storing a complete copy of the data, and Phoenix retains historical row versions to reconstruct changes. Here is a small example of what CDC usage in Phoenix looks like for a simple ORDERS table. SQL -- Create a table and enable CDC CREATE TABLE orders ( order_id VARCHAR PRIMARY KEY, status VARCHAR ); CREATE CDC cdc_orders ON orders; -- Insert an order UPSERT INTO orders VALUES ('order-101', 'CREATED'); -- Update the order UPSERT INTO orders VALUES ('order-101', 'SHIPPED'); -- Query changes, including before and after images SELECT /*+ CDC_INCLUDE(PRE, POST) */ PARTITION_ID() AS partition_id, PHOENIX_ROW_TIMESTAMP() AS event_time, order_id, "CDC JSON" FROM cdc_orders ORDER BY PHOENIX_ROW_TIMESTAMP(); -- Conceptual results: -- INSERT: partition_id = R1, PRE = null, POST = {status: CREATED} -- UPDATE: partition_id = R1, PRE = {status: CREATED}, POST = {status: SHIPPED} -- partition_id is the hbase region identifier for the change The CDC query returns change records along with their partition identifiers, which are HBase Region IDs, timestamps, and requested pre/post images. CDC Streams and Partition Metadata The initial Phoenix CDC implementation focused on querying change records within a time range. However, typical stream consumers have additional requirements. For higher throughput, they need to discover and consume multiple shards in parallel. As shards split or merge, consumers also need to track their lineage to discover new shards and ensure parent shards are fully consumed before processing their children. Finally, consumers need a way to resume from their last processed position after failures. While checkpointing is typically the consumer's responsibility, the streaming interface must provide sequence numbers and iterators to support it. To support these requirements, we extended Phoenix with stream metadata and shard-tracking capabilities (PHOENIX-7456). Phoenix organizes CDC changes into streams containing partitions, where each partition corresponds to an HBase region of the underlying data table. The PARTITION_ID() function associates each change record with the region where it originated, allowing consumers to retrieve changes from individual partitions. Two system tables maintain the stream metadata: SYSTEM.CDC_STREAM_STATUS tracks CDC stream objects and their lifecycle, including initialization and active states.SYSTEM.CDC_STREAM stores partition metadata, including partition identifiers, parent-partition relationships, start and end times, and row-key boundaries. Streams and partitions have separate lifecycles. A stream can remain active while its underlying partitions change as HBase regions split or merge. The metadata therefore needs to track not just the currently active partitions, but also their relationships with previously existing partitions. Bootstrapping and Tracking Partition Topology It is not sufficient for a consumer to simply query HBase for its current regions since it may still be processing changes from regions that have already split or merged. Persisting partition history allows consumers to finish reading closed partitions and discover their successors without losing track of unconsumed changes. When CDC is enabled on an existing table, Phoenix first needs to discover the HBase regions that already exist. A background initialization task populates SYSTEM.CDC_STREAM with the initial region metadata, including each region's encoded identifier, start time, and row-key boundaries. After initialization, Phoenix needs to keep this metadata updated as the underlying HBase region topology changes. HBase provides coprocessor hooks that allow custom logic to run in response to region lifecycle events, enabling Phoenix to update its stream metadata whenever a region split or merge completes. Phoenix uses the HBase Master coprocessor hooks postCompletedSplitRegionAction and postCompletedMergeRegionsAction to track these changes. When a region splits, the parent partition is marked as closed, and entries are created for the two daughter partitions. Similarly, when regions merge, the parent partitions are closed, and a new partition is added with references to all its parents. In both cases, Phoenix preserves the parent-child relationships so consumers can reconstruct the partition topology even after the underlying HBase regions have changed. Consider our ORDERS table that initially has two HBase regions, R1 and R2. When CDC is enabled, Phoenix bootstraps the stream metadata for both regions. Suppose R2 later splits into R3 and R4. Subsequently, R1 and R3, which are adjacent regions, merge into a new region R5. The resulting lineage looks like this, with R4 and R5 as the active regions: For the above partition lineage, the metadata in the SYSTEM.CDC_STREAM table would look something like the following. For simplicity, some columns are not shown here, but each partition metadata row also carries the table and stream name. partition idparent partition idstart timeend time R1 NULL T0 T2 R2 NULL T0 T1 R3 R2 T1 T2 R4 R2 T1 NULL R5 R1 T2 NULL R5 R3 T2 NULL The region identifiers and timestamps are illustrative. T0 represents the initial bootstrap, T1 the split, and T2 the merge. A null end time indicates an active HBase region receiving writes. This example shows how Phoenix maintains partition lineage across region topology changes. R1 and R2 initially have no parents. When R2 splits, it is marked as closed, and R3 and R4 are added with R2 as their parent. Later, when R1 and R3 merge, both partitions are closed, and R5 is created with references to both parents. R4 remains active. The merge case also influenced the metadata schema. PARENT_PARTITION_ID is included in the composite primary key of SYSTEM.CDC_STREAM, allowing multiple rows for the same child partition, one for each parent. This avoids storing multiple parent identifiers in a single field and makes it easier to query partition lineage. Together, the background bootstrap process and the region split/merge hooks allow Phoenix to maintain a history of CDC partition topology as the underlying HBase table evolves. This metadata provides the foundation for partition-aware stream consumption. Implementing DynamoDB Streams APIs in Phoenix Adapters Phoenix Adapters implements four DynamoDB Streams APIs: ListStreams, DescribeStream, GetShardIterator, and GetRecords. Together, these APIs allow existing DynamoDB Streams clients to discover streams, navigate their shards, and consume change records from Apache Phoenix. The implementation uses Phoenix's CDC objects for retrieving change records and its stream metadata tables for discovering streams and their partitions. ListStreams Every DynamoDB Streams consumer starts with the ListStreams API. It returns the streams available for consumption for a given table name. Phoenix uses the stream information stored in SYSTEM.CDC_STREAM_STATUS and converts it into the DynamoDB Streams response format. Each stream is returned with a table name, stream ARN, and stream label. Here is an example response: JSON { "Streams": [ { "TableName": "ORDERS", "StreamArn": "arn:aws:dynamodb:us-west-2:000000000000:table/ORDERS/cdc_orders/2026-10-14T10:00:00.000", "StreamLabel": "2026-10-14T10:00:00.000" } ] } Since Phoenix Adapters can run outside AWS, the stream ARN is constructed in the format expected by DynamoDB clients, using placeholder AWS region and account identifiers. The stream label identifies the stream's creation time. The API also supports pagination using Limit and ExclusiveStartStreamArn, allowing clients to discover streams across multiple requests. DescribeStream Once the consumer has the stream it wants to consume from, it calls DescribeStream to retrieve the metadata for the shards available in that stream for consumption. Phoenix Adapters constructs the DescribeStream response using metadata maintained by Apache Phoenix. Stream and partition information comes from SYSTEM.CDC_STREAM_STATUS and SYSTEM.CDC_STREAM, while StreamViewType, which determines whether change records include old images, new images, or both, is retrieved from Phoenix table metadata. The partition identifiers, parent-child relationships, and start/end timestamps are then used to construct the shard metadata. Consider the example from Section 2, where the ORDERS table initially has two regions, R1 and R2, and R2 subsequently splits into R3 and R4. An abbreviated DescribeStream response after the split would look like this: JSON { "StreamDescription": { "StreamArn": "...", "StreamLabel": "2026-10-14T10:00:00.000", "StreamStatus": "ENABLED", "StreamViewType": "NEW_AND_OLD_IMAGES", "TableName": "ORDERS", "Shards": [ { "ShardId": "shard-R2", "SequenceNumberRange": { "StartingSequenceNumber": "T0||00000", "EndingSequenceNumber": "T1||99999" } }, { "ShardId": "shard-R3", "ParentShardId": "shard-R2", "SequenceNumberRange": { "StartingSequenceNumber": "T1||00000" } }, { "ShardId": "shard-R4", "ParentShardId": "shard-R2", "SequenceNumberRange": { "StartingSequenceNumber": "T1||00000" } } ] } } Shard identifiers are simplified for illustration, and || in Sequence Numbers denotes concatenation. Although Apache Phoenix CDC supports region merges and tracks multiple parent partitions, Phoenix Adapters disables HBase region merges (MERGE_ENABLED=false) for tables with DynamoDB Streams enabled. This is because DynamoDB Streams supports shard splits but does not expose merging shards. Disabling merges keeps the underlying HBase partition topology compatible with the DynamoDB Streams shard model. The example shows how closed shards have an EndingSequenceNumber, while active shards do not. The sequence numbers are constructed using partition timestamps with additional padding to identify individual records. The sequence-number format and the purpose of this padding are explained in a separate section below. GetShardIterator GetShardIterator allows a client to obtain an iterator representing the position from which it wants to start consuming records within a shard. The API supports four starting positions, which Phoenix Adapters handles as follows: TRIM_HORIZON: Uses the shard's starting sequence number to begin reading from the earliest available position.LATEST: Uses the current clock time as the starting position to consume new changes.AT_SEQUENCE_NUMBER: Starts reading at the specified sequence number.AFTER_SEQUENCE_NUMBER: Starts reading immediately after the specified sequence number. Phoenix Adapters returns an opaque shard iterator that contains all the information needed to construct a Phoenix CDC SQL query. This includes the table name, CDC object, stream view type, partition identifier, and starting sequence number. Conceptually, the iterator looks like this: Plain Text shardIterator/<tableName>/<cdcObject>/<streamType>/<partitionId>/<startSeqNum> tableName: The underlying Phoenix table.cdcObject: The Phoenix CDC object used to query changes.streamType: The configured stream view type, to determine which row images to return.partitionId: The CDC partition from which records will be retrieved.startSeqNum: The sequence position from which consumption should begin. Since the iterator contains all the information required to construct the SQL query, Phoenix Adapters does not need to maintain server-side cursors for individual consumers. Any instance of the stateless HTTP service can process a subsequent GetRecords request using the iterator supplied by the client. GetRecords To start consuming records from a shard starting from a given position, the client would provide the ShardIterator it received from the GetShardIterator response to the GetRecords API. Phoenix Adapters decodes the iterator to identify the CDC object, partition, and starting sequence position. It then constructs a SQL query against the CDC object to retrieve changes from that position. A simplified version of the query is: SQL SELECT /*+ CDC_INCLUDE(PRE, POST) */ * FROM <cdcObject> WHERE PARTITION_ID() = <partitionId> AND PHOENIX_ROW_TIMESTAMP() >= <timestamp> ORDER BY PHOENIX_ROW_TIMESTAMP() ASC LIMIT <limit> OFFSET <offset> The partition identifier restricts the query to a particular shard, while the timestamp and offset identify where consumption should resume. The CDC_INCLUDE hint retrieves the previous and updated row images needed for the DynamoDB Streams response. Handling Sequence Numbers DynamoDB Streams assigns a sequence number to each change record, identifying its position within a shard. These sequence numbers allow consumers to read records in order and resume consumption from a particular position. DynamoDB Streams also guarantees that changes to the same item appear in the order they occurred, although it does not guarantee a global ordering across different items. Phoenix CDC provides a timestamp for each change through a row timestamp. However, multiple changes to different HBase row keys can occur within the same millisecond and therefore share the same timestamp. Using the timestamp directly as a sequence number would not uniquely identify these records. To address this, Phoenix Adapters constructs sequence numbers by combining the millisecond timestamp with an N-digit offset. Records sharing the same timestamp are returned in HBase row-key scan order and assigned incrementing offsets. N is configurable, with a default value of 5, allowing up to 100,000 distinct sequence positions for records sharing the same timestamp within a partition. For updates to the same row key, Phoenix's mutation and timestamp-handling logic is important for preserving the order of successive changes. For example, rowkeytimestampsequence number order-101 100 10000000 order-102 121 12100000 order-103 121 12100001 order-104 121 12100002 order-105 156 15600000 Sequence numbers/timestamps are shortened for readability. The actual implementation uses fixed-width numeric strings. The offset resets when the timestamp changes. This gives records within a shard a distinct position without maintaining a global sequence number counter which writes to different rowkeys would need to synchronize on. When processing a GetRecords request, Phoenix Adapters splits sequence number from the shard iterator back into its timestamp and offset components. The timestamp is used in the PHOENIX_ROW_TIMESTAMP() predicate, while the offset is applied through the SQL OFFSET clause to skip records already consumed. Returning Records and NextShardIterator Phoenix Adapters converts the CDC query results into DynamoDB Streams records. Each record includes an event type (INSERT, MODIFY, or REMOVE), the item's primary key, a sequence number, and the appropriate old or new item images based on the configured StreamViewType. Event type is inferred from the PRE/POST images in the CDC results, which also contain the row key, and the sequence number is generated based on the steps described in the previous section. Along with the records, GetRecords returns a NextShardIterator (NSI), which the client uses to continue reading from where the previous request stopped. As records are processed, the adapter tracks the timestamp and offset of the last record. The offset increments for records sharing the same timestamp and resets to zero when the timestamp changes. After processing the batch, the next iterator is constructed using the last record's timestamp and its offset incremented by one. Consider the example above, with a client requesting two records per call: records returnedsequence number for nsi Records Returned Sequence Number for NSI order-101, order-102 12100001 order-103, order-104 12100003 order-105 15600001 After the first call, the NSI contains sequence number 12100001, representing timestamp 121 and offset 1. The client passes this iterator unchanged in its next GetRecords request. Phoenix Adapters splits the sequence number into its timestamp and offset components and constructs a query equivalent to: SQL SELECT /*+ CDC_INCLUDE(PRE, POST) */ * FROM <cdcObject> WHERE PARTITION_ID() = <partitionId> AND PHOENIX_ROW_TIMESTAMP() >= 121 ORDER BY PHOENIX_ROW_TIMESTAMP() ASC LIMIT 2 OFFSET 1; This query skips order-102, which was already returned at timestamp 121, and retrieves order-103 and order-104. The following NSI advances to 12100003, allowing the next request to skip all three records at timestamp 121 and continue with order-105. This process allows clients to resume consumption across batches using the returned iterator, without Phoenix Adapters maintaining server-side cursors. It relies on HBase's deterministic row-key scan order to consistently return records sharing the same timestamp in the same order across requests. Phoenix Adapters also checks whether the underlying partition has closed and whether any unread records remain. Once a closed partition has been fully consumed, GetRecords returns a null NextShardIterator, signaling that the consumer has reached the end of that shard. Compatibility Validation Implementing the published interface of a technically complex API is certainly challenging, but it is the behavior across different inputs and edge cases which makes compatibility hard to achieve. DynamoDB provides extensive API documentation, but not every detail of its behavior is explicitly specified, so a great deal of what applications depend on is undocumented. One good way to establish that is to observe what DynamoDB does and record it. Phoenix Adapters includes comprehensive integration tests that compare the results of API operations against AWS DynamoDB Local. These tests help verify that the implementation produces compatible results and catch regressions as the project evolves. One good example is BinaryStreamsIT, which validates change records and old/new item images across inserts, updates, and deletes for tables with primary keys in the binary data format. Community-developed conformance suites provide another way to test compatibility. One such project is Parity Suite, which tests DynamoDB-compatible implementations against behavior observed from the actual AWS DynamoDB service. We ran Parity Suite (v3.6.1) against Phoenix Adapters (as of commit 04d5cbd9d5), and all DynamoDB Streams tests passed, covering INSERT, MODIFY, and REMOVE events, shard and iterator behavior, primary keys, old and new item images, and different stream view types. These results provide additional validation of the Streams implementation for the scenarios covered by the suite Conclusion Together, these four APIs allow existing DynamoDB Streams clients to discover streams, navigate shards, and consume changes from Apache Phoenix. Phoenix Adapters achieves this by exposing Phoenix's SQL-based CDC capabilities and stream metadata through a DynamoDB-compatible interface. The implementation is validated through integration tests against DynamoDB Local and third-party conformance testing. Applications can also use the Kinesis Client Library (KCL) through the DynamoDB Streams Kinesis Adapter, which uses these four APIs to discover shards and consume records. This allows existing KCL-based consumers to work with Phoenix Adapters without implementing their own stream-consumption logic. More broadly, this approach demonstrates how an existing database's CDC capabilities can be exposed through a familiar streaming API. By maintaining compatibility at the API level, applications can continue using their existing client libraries and streaming integrations while working with a different database backend.
Almost every distributed system ends up with an asynchronous messaging layer. One service publishes an event, several others consume it at their own pace, and the publisher doesn't wait for them. On Google Cloud, that layer is Pub/Sub. On AWS, it's usually two services wired together: SNS for fan-out and SQS for durable queues. The building blocks are cut differently, and it shows in your code: how you publish, acknowledge, retry, and order messages. This article walks through Pub/Sub in Java, maps it onto SNS and SQS, and shows how MultiCloudJ, an open-source Java SDK from Salesforce, puts both behind one portable API. The Google Cloud Pub/Sub Model Pub/Sub has two core resources: Topic. A named channel that publishers send messages to. Topics are global resources: a publisher in us-east1 and a subscriber in europe-west1 use the same topic without any cross-region plumbing.Subscription. A named, durable stream of messages from one topic. Each subscription gets its own copy of every message published after it was created. Several subscribers on the same subscription share the work, and each message goes to one of them. So fan-out means many subscriptions, and load-balancing means many subscribers on one subscription, with no extra wiring for either. One topic, three subscriptions: two billing workers share a pull subscription, analytics exports to BigQuery, and email is pushed to Cloud Run. Delivery: Pull, Push, or Export Pull. The subscriber asks for messages. The Java client library uses StreamingPull, a long-lived bidirectional gRPC stream, so messages flow as soon as they arrive.Push. Pub/Sub sends each message as an HTTPS POST to an endpoint you own, such as a Cloud Run service. It can attach a Google-signed OIDC token so the endpoint can verify the caller. A success status (102, 200, 201, 202, or 204) is an ack.Export. BigQuery and Cloud Storage subscriptions write messages straight into a table or bucket, with no consumer code at all. Acknowledgment and the Ack Deadline Delivery is at-least-once. A received message must be acked within the subscription's ack deadline (10 seconds by default, up to 600), or Pub/Sub redelivers it. ModifyAckDeadline extends the deadline, and setting it to 0 is a nack: the message becomes available for redelivery right away. The Java client extends leases in the background while your callback runs, for up to an hour by default. A subscription retains unacked messages for 7 days by default, configurable from 10 minutes to 31 days. Topics can also retain messages for up to 31 days, so a new or rewound subscription can replay history with Seek. Publishing and Consuming in Java The native publisher batches messages and returns a future per message. build() throws IOException: Java import com.google.api.core.ApiFuture; import com.google.cloud.pubsub.v1.Publisher; import com.google.protobuf.ByteString; import com.google.pubsub.v1.PubsubMessage; import com.google.pubsub.v1.TopicName; Publisher publisher = Publisher.newBuilder(TopicName.of("my-project", "orders")) .setEnableMessageOrdering(true) // required if you set ordering keys .build(); PubsubMessage message = PubsubMessage.newBuilder() .setData(ByteString.copyFromUtf8("{\"orderId\":\"o-123\",\"total\":42.50}")) .putAttributes("type", "order.created") // attributes are string key/value pairs .setOrderingKey("customer-42") // ordered per key, not per topic .build(); ApiFuture<String> messageId = publisher.publish(message); The subscriber registers a callback that acks or nacks each message: Java import com.google.cloud.pubsub.v1.MessageReceiver; import com.google.cloud.pubsub.v1.Subscriber; import com.google.pubsub.v1.ProjectSubscriptionName; MessageReceiver receiver = (msg, consumer) -> { try { process(msg.getData().toStringUtf8(), msg.getAttributesMap()); consumer.ack(); } catch (Exception e) { consumer.nack(); // redeliver now } }; Subscriber subscriber = Subscriber.newBuilder( ProjectSubscriptionName.of("my-project", "orders-billing"), receiver) .build(); subscriber.startAsync().awaitRunning(); Both use Application Default Credentials, so on GKE, Cloud Run, or GCE, no keys appear in code. The Features That Matter in Production Ordering keys. Messages that share an ordering key are delivered in publish order, as long as the subscription has message ordering enabled, and the messages are published in the same region. Messages with different keys can still be processed in parallel.Dead-letter topics. After a configurable number of delivery attempts (5 to 100), Pub/Sub forwards the message to a dead-letter topic instead of retrying forever.Filtering. A subscription can carry a filter on message attributes, such as attributes.type = "order.created", so consumers only get what they care about.Exactly-once delivery. Pull subscriptions can turn on exactly-once delivery. Pub/Sub then won't redeliver a message once its ack has succeeded, and the Java client's AckReplyConsumerWithResponse tells you whether the ack went through. The guarantee holds when subscribers connect in the same region. AWS for Comparison: SNS Plus SQS SNS is the topic: it pushes each message to its subscribers immediately, and consumers can't poll it. SQS is the durable queue: consumers poll it, and a message stays until someone deletes it. For Pub/Sub-style fan-out, you subscribe one SQS queue per consumer group to an SNS topic. The same topology on AWS: an SNS topic fans out to one SQS queue per consumer group. The concepts map closely; the table below lines them up. A few AWS details have no Pub/Sub equivalent: Each queue needs an access policy that lets the topic send to it.SQS has no ack call. You DeleteMessage with the receipt handle from ReceiveMessage.There is no streaming pull. ReceiveMessage long-polls for up to 20 seconds.FIFO adds a 5-minute deduplication window keyed by MessageDeduplicationId.Unless raw message delivery is on, each SQS body is an SNS JSON envelope with your payload in its Message field. Side by Side ConceptGoogle Cloud Pub/SubAWS SNS + SQSServices involvedOneTwo, wired togetherFan-outMultiple subscriptions on a topicSNS topic subscribed by multiple SQS queuesDurable consumer streamSubscriptionSQS queueConsumeStreamingPull, push, or export to BigQuery/GCSSQS polling (max 10 per call), or SNS push to Lambda/HTTPSAckAcknowledgeDeleteMessageAck windowAck deadline: 10s default, 600s maxVisibility timeout: 30s default, 12h maxNackModifyAckDeadline to 0ChangeMessageVisibility to 0OrderingOrdering keys on any topicFIFO topics and queues with MessageGroupIdDead lettersDead-letter topic, 5–100 attemptsRedrive policy, maxReceiveCountMax message size10 MB1 MiB (SQS), 256 KiB by default on SNS, configurable to 1 MiBRetentionSubscription: 7 days by default, up to 31. Topic: up to 31 daysSQS: 4 days by default, up to 14. SNS FIFO archive: up to 365 daysReplaySeek to a timestamp or snapshot, on any topicSNS FIFO archive and replay only. Standard topics and SQS can't replay Pub/Sub has fewer moving parts. A new consumer group is one subscription. On AWS it's a queue, a subscription, and a queue policy.Ordering is cheaper to adopt on Pub/Sub. You add a key to a topic you already have. On AWS, you need FIFO resources from the start, because you can't convert a standard queue to FIFO.SQS gives you a longer ack window. Long-running jobs fit the 12-hour visibility timeout. On Pub/Sub, you rely on the client extending the lease.Replay is broader on Pub/Sub. Seek works on any subscription, which makes reprocessing after a bad deploy a routine operation. On AWS, only FIFO topics with archiving enabled can replay. One Interface for Both: MultiCloudJ If your service runs on both clouds, these differences become if (cloud == GCP) branches through your messaging code. MultiCloudJ removes them. Its pubsub module has two portable clients, TopicClient and SubscriptionClient. They delegate to an abstract driver that owns batching, prefetching, ack batching, and error mapping, and a provider module per cloud makes the API calls. Providers are discovered with Java's ServiceLoader and selected by an ID string, so switching clouds is a configuration change. MultiCloudJ's layers: one portable API, provider drivers underneath. Add the Dependencies Add the client plus a provider module for each cloud. Your code never imports the provider modules: XML <dependency> <groupId>com.salesforce.multicloudj</groupId> <artifactId>pubsub-client</artifactId> <version>0.4.11</version> </dependency> <!-- Google Cloud Pub/Sub --> <dependency> <groupId>com.salesforce.multicloudj</groupId> <artifactId>pubsub-gcp</artifactId> <version>0.4.11</version> </dependency> <!-- AWS SNS and SQS --> <dependency> <groupId>com.salesforce.multicloudj</groupId> <artifactId>pubsub-aws</artifactId> <version>0.4.11</version> </dependency> Only the provider ID and resource name change between clouds: CloudTopic provider IDTopic nameSubscription provider IDSubscription nameGoogle Cloudgcpprojects/my-project/topics/ordersgcpprojects/my-project/subscriptions/orders-billingAWS (SNS)awssnsarn:aws:sns:us-east-1:123456789012:ordersawsSQS queue name, e.g. orders-billingAWS (SQS)awssqsSQS queue name or queue URLawsSQS queue name, e.g. orders-billing On AWS, a subscription is always an SQS queue, whether you publish to SNS or straight to SQS. Send a Message With MultiCloudJ Java import com.salesforce.multicloudj.pubsub.client.TopicClient; import com.salesforce.multicloudj.pubsub.driver.Message; public class PublishOrder { public static void main(String[] args) throws Exception { String provider = System.getenv("PUBSUB_TOPIC_PROVIDER"); // gcp, awssns, or awssqs String topicName = System.getenv("PUBSUB_TOPIC"); TopicClient.TopicClientBuilder builder = TopicClient.builder(provider) .withTopicName(topicName); String region = System.getenv("REGION"); // e.g. us-east-1 on AWS if (region != null) { builder.withRegion(region); } try (TopicClient topic = builder.build()) { Message message = Message.builder() .withBody("{\"orderId\":\"o-123\",\"total\":42.50}") .withMetadata("type", "order.created") .build(); topic.send(message); // blocks until accepted } // close() flushes pending batches } } The driver batches concurrent sends: up to 1,000 per Publish on GCP, and 10 per PublishBatch or SendMessageBatch on AWS. Metadata becomes Pub/Sub attributes or SNS/SQS message attributes. Receive Messages With MultiCloudJ Java import com.salesforce.multicloudj.pubsub.client.SubscriptionClient; import com.salesforce.multicloudj.pubsub.driver.Message; import java.nio.charset.StandardCharsets; import java.time.Duration; public class ConsumeOrders { public static void main(String[] args) throws Exception { String provider = System.getenv("PUBSUB_SUBSCRIPTION_PROVIDER"); // gcp or aws String subscriptionName = System.getenv("PUBSUB_SUBSCRIPTION"); SubscriptionClient.SubscriptionClientBuilder builder = SubscriptionClient.builder(provider) .withSubscriptionName(subscriptionName) .withNackVisibilityTimeout(Duration.ofSeconds(30)); // nack delay, default 0 String region = System.getenv("REGION"); if (region != null) { builder.withRegion(region); } try (SubscriptionClient subscription = builder.build()) { while (!Thread.currentThread().isInterrupted()) { Message msg = subscription.receive(); // blocks; the driver prefetches try { String body = new String(msg.getBody(), StandardCharsets.UTF_8); process(body, msg.getMetadata()); subscription.sendAck(msg.getAckID()); // batched in the background } catch (Exception e) { subscription.sendNack(msg.getAckID()); // redelivered after 30s } } } } private static void process(String body, java.util.Map<String, String> metadata) { // your business logic } } This loop runs unchanged on both clouds. The driver translates each call: Portable callGCP driverAWS driverreceive()Pull, up to 1,000 per callReceiveMessage, up to 10 per callsendAck(id)AcknowledgeDeleteMessageBatchsendNack(id)ModifyAckDeadline, capped at 600sChangeMessageVisibilityBatch, capped at 12hgetMetadata()Message attributesSQS attributes, merged with SNS attributesgetAttributes()GetSubscription (name, topic)GetQueueAttributes (queue ARN) The driver also absorbs differences you'd otherwise handle yourself: Adaptive prefetching. receive() reads from a buffer the driver keeps about 2 seconds deep, based on your processing rate, so messages don't sit past their ack deadline.Ack batching. sendAck returns immediately; acks flush in batches of up to 1,000 on GCP and 10 on AWS. sendAcks returns a CompletableFuture if you need confirmation.Nack backoff. sendNack(id, Duration) overrides the subscription default per message. The GCP driver groups nacks by deadline, since ModifyAckDeadline takes one deadline per request.SNS envelope unwrapping. Without raw delivery, the AWS driver unwraps the SNS envelope, so you see the original body and metadata, as on GCP.FIFO through metadata. On AWS, the MessageGroupId and DeduplicationId metadata keys become the native FIFO fields.Portable errors. Provider exceptions map to one SubstrateSdkException hierarchy. What the Abstraction Doesn't Hide Resources are provisioned elsewhere. Topics, subscriptions, queues, SNS-to-SQS wiring, and dead-letter policies still come from Terraform or your platform tooling.Pub/Sub-only features stay native. Filters, exactly-once delivery, push and export subscriptions, and Seek are configured on the resources or used through the native client. The GCP driver also doesn't set ordering keys.The GCP driver uses unary Pull, not StreamingPull. That keeps one batching model across clouds, but the native Subscriber will deliver lower latency for very high-throughput subscriptions.Ack windows still differ. The same nack timeout is capped at 10 minutes on GCP and 12 hours on AWS. Size your processing time to the smaller window. Conclusion Google Cloud Pub/Sub folds fan-out, durable queuing, and replay into one service. AWS gets there by combining SNS and SQS, with more resources to wire and different API verbs. On Google Cloud, subscriptions, ordering keys, and Seek give you more with less configuration. If you run on both, keep the differences out of your business logic: put MultiCloudJ's TopicClient and SubscriptionClient at the boundary, pick the provider in configuration, and use the native client for the few features only one cloud offers.
Every new cluster brings the same chore: copy the registry password into every namespace that pulls private images, and repeat it when the password rotates. Clusters are created dynamically, so the chore never ends, and each copy is one more place where the password can expire or leak. Kubernetes 1.34+ offers a way out: the kubelet can hand a credential provider plugin the ServiceAccount token of the pod whose image it is pulling, and the plugin swaps it at the registry for short-lived, read-only credentials. A ServiceAccount token is issued for a specific pod for a limited time and does not sit in any manifest. The registry decides which tokens it trusts. That is closer to zero trust: the workload holds no long-lived secret that could be stolen and used from somewhere else. The scheme works, but when it fails, the cause is hard to find. The pod goes into ImagePullBackOff, and the events show only a generic registry answer: failed to resolve reference ... unexpected status from HEAD request. The real cause is written by the kubelet and appears only in its log on the node: Plain Text ak-kubelet-provider: https://ak.test: 401 CI JWT did not match any identity mapping That line does not appear on its own: the kubelet, the nodes' permissions, and the registry all have to be configured first. The examples use a plugin I wrote and the open-source Artifact Keeper registry, and they all come from my test cluster. What the Registry Has to Do The scheme needs a registry that accepts Kubernetes ServiceAccount tokens, which are OIDC tokens signed by the cluster, and issues short-lived credentials in exchange. Any registry that can verify the cluster's OIDC tokens and issue such credentials fits. The examples below use Artifact Keeper 1.11, which has this exchange built in. How the kubelet Passes the ServiceAccount Token to the Plugin The kubelet can obtain image credentials from an external executable, called an image credential provider. It runs on every node. The kubelet writes a JSON request with the image name to its stdin and reads a username, a password, and a cache duration from its stdout. Kubernetes 1.34 added the ServiceAccount token of the pod being started to that request (KEP-4412, the tokenAttributes field in the config). Before that, a plugin saw only the image name and could rely only on the node's identity. Now it knows which pod asks for the image and can exchange the token for access granted to that ServiceAccount. The config for this plugin looks like this: YAML apiVersion: kubelet.config.k8s.io/v1 kind: CredentialProviderConfig providers: - name: ak-kubelet-provider matchImages: ["ak.test"] defaultCacheDuration: "5m" apiVersion: credentialprovider.kubelet.k8s.io/v1 args: - --url=https://ak.test tokenAttributes: serviceAccountTokenAudience: artifact-keeper cacheType: ServiceAccount requireServiceAccount: true serviceAccountTokenAudience says who the token is issued for. It needs a dedicated value that differs from the API server's audience. With the API server's audience, the registry would accept the token of any pod, and the token the plugin sends to the registry would also be valid against the API server. Artifact Keeper refuses to create such a provider and answers 400. The whole exchange is shown in the diagram below. The image is not on the node yet, so the kubelet calls the plugin. The pod in team gets access because the registry has a mapping for the namespace team, a rule that admits ServiceAccounts from it. The plugin returns a cacheDuration to the kubelet, equal to the lifetime of the issued token minus 60 seconds. With cacheType: ServiceAccount the kubelet caches credentials per ServiceAccount. A second pod of the same ServiceAccount takes them from the cache, while a pod of another ServiceAccount calls the plugin itself. What the Cluster Needs Besides the Plugin The plugin works only together with a few cluster settings. Without them, the image does not arrive, and the cause is hard to find. Nodes must be allowed to request tokens for the audience. Since Kubernetes 1.33, ServiceAccountNodeAudienceRestriction is in effect. The API server does not issue a node a token with an audience that is not in the pod's projected volumes unless the node has been explicitly allowed. Without that permission, the kubelet logs is not authorized to request tokens for this audience and pulls the image without credentials. The pod gets a generic denial, as if there were no plugin at all. The permission is granted by a ClusterRole bound to the group system:nodes: YAML rules: - apiGroups: [""] resources: ["artifact-keeper"] verbs: ["request-serviceaccounts-token-audience"] resources here is the audience itself. If nodes have no permission for the audience, the plugin does not run at all: the registry receives neither a request nor an error, and the events show a generic denial. kubelet flags. You need --image-credential-provider-config and --image-credential-provider-bin-dir. My kind config with kubeadmConfigPatches did not apply them, so I appended the flags to /var/lib/kubelet/kubeadm-flags.env on the node and restarted the kubelet. If the plugin is not called at all, the kubelet log has no line from ak-kubelet-provider. Then check matchImages (the image host must match) and the audience permission from the previous point. The Registry Swaps the Token for Read-Only Access To accept ServiceAccount tokens and issue credentials in exchange, Artifact Keeper 1.11 has a CI OIDC provider of type kubernetes. First I create the provider. On my test setup, the registry runs inside the same kind cluster: I give it the signing keys statically, and it does not have to reach the API server's discovery endpoint: Shell kubectl get --raw /openid/v1/jwks > jwks.json jq -n --slurpfile jwks jwks.json '{ name: "prod-cluster", provider_type: "kubernetes", issuer_url: "https://kubernetes.default.svc.cluster.local", audience: "artifact-keeper", key_source: "static", static_jwks: $jwks[0]}' | curl -X POST https://ak.test/api/v1/admin/ci-oidc \ -H "Authorization: Bearer $ADMIN_TOKEN" -H "Content-Type: application/json" -d @- Then I create a mapping that defines which ServiceAccounts get access and binds them to a group with read permission: Shell curl -X POST https://ak.test/api/v1/admin/ci-oidc/$PROVIDER_ID/mappings \ -H "Authorization: Bearer $ADMIN_TOKEN" -H "Content-Type: application/json" \ -d '{"name":"team-ns","priority":10, "claim_filters":{"/kubernetes.io/namespace":"team"}, "group_binding_ids":["'$GROUP_ID'"]}' A key that starts with / is a JSON Pointer into the token's claims. This single namespace filter admits every ServiceAccount in team. The match is exact: team does not admit team-sandbox. All ServiceAccounts admitted by one mapping share one registry account, in my case ci-1007c2257aba. You can tell them apart in the registry log, which records the namespace, ServiceAccount, pod and node of every exchange. A Foreign Namespace Is Denied, a Mapped One Pulls the Image I started a kind 1.34.3 cluster and installed Artifact Keeper 1.11.1 inside it. I built the plugin from main for arm64 musl. Results: Check Result Pod in team with ServiceAccount app Image pulled on the first attempt, no imagePullSecrets Second ServiceAccount other in team, same mapping Pulled, the exchange returned 200 Pod in namespace outsider, which has no mapping ImagePullBackOff, the kubelet log shows 401 CI JWT did not match any identity mapping, as in the introduction push with the issued token denied: Token does not have required scope: write:artifacts, on both blobs and the manifest Create an API token with this token 403 Create a provider with the API server's audience 400 The token the plugin receives can only read. The registry limits it by provider type and does not consult the group's permissions: even if the group has write access, this token writes nothing. An Image Already on the Node Hides the Denial The outsider check fooled me at first. I started a pod in the foreign namespace and it came up. The reason: the image was already on the node after the first pod. The kubelet does not pull an image it already has, so the plugin is never reached. The same pod from a foreign namespace either starts or fails, depending on imagePullPolicy and on whether the image is already on the node. In the first case, the registry never hears about it. To test a denial, you need imagePullPolicy: Always or an image that is not on the node. Until you do that, any check of the kind "a foreign ServiceAccount must not get in" passes green. The Plugin: One Rust Binary, No Token in the Logs It is a single static Rust binary of about 1.7 MB. The HTTP client is ureq with rustls, and there is no async runtime. It builds for x86_64 and aarch64 musl and is signed with cosign. There is no async runtime on purpose: the process lives for tens of milliseconds and needs a single request. The binary runs as root on every node, so it follows a few rules, each covered by a test: The token never reaches the logs at any level, and if the registry echoes it in an error message, the plugin replaces it with [REDACTED];http:// is rejected before any request is sent, so the token cannot travel over an open channel;Redirects are not followed, so the token cannot be sent to another address;The whole exchange runs under a single timeout, 10 seconds by default. On failure, the plugin writes one line to stderr and exits with code 1. The kubelet records it in its own log and pulls the image without credentials. That is why pod events show only a generic denial, while the details sit on the node: journalctl -u kubelet | grep ak-kubelet-provider. EKS, GKE and AKS: A Recipe Exists, Real Clusters Have Not Been Tried On these platforms, you cannot set kubelet flags directly. The schemes below are tested in parts and on kind, so treat them as a working plan without guarantees. EKS (Amazon Linux 2023). nodeadm writes a config.json with a single provider, ecr-credential-provider. A script in the user data copies that file and adds an entry for the plugin. The script passes the file with the added entry to the kubelet as a second --image-credential-provider-config flag. Of two identical flags, the kubelet takes the last one, so it reads that file, and the ECR entry stays in it: EKS system images still come from ECR. This does not work on Bottlerocket, EKS Auto Mode, or Fargate. GKE Standard and AKS. Neither Google nor Microsoft lets you add a plugin through their API. For them, the repository has a privileged DaemonSet: it finds the provider config on the kubelet's command line, adds the plugin there, and restarts the kubelet. If the kubelet does not come back after the restart, the DaemonSet restores the previous config. The vendors do not support this approach and may break it with a node image update. The DaemonSet pod runs as root on every node, so only cluster administrators should be able to change its ConfigMap. 19 ms per Call, and a Cache That Spares Repeat Exchanges The measurements were taken on a single kind node (a laptop, with the registry in the same cluster): network latency is close to zero. The numbers show the cost of the plugin itself, not of your network. One plugin call takes about 19 ms including process start and the TLS handshake: 100 sequential calls took 1.9 s.200 calls, 20 in parallel, finished in 1.1 s with no errors.The registry token's lifetime in my setup is 30 minutes. For a one-hour ServiceAccount token, the plugin returned a cacheDuration of 1740 s: 30 minutes minus a 60-second margin.20 pods of one ServiceAccount that had not yet been seen on the node produced 2 exchanges instead of 20. Most likely the second exchange happened before the cache was filled. cacheDuration follows the shorter of the two tokens: with a 10-minute ServiceAccount token, the plugin returned 539 s, with a one-hour token 1740 s. What My Tests Do Not Cover Real EKS, GKE, and AKS clusters. The only real run is on kind.Kubernetes releases newer than 1.34.3. All tests ran on 1.34.3, the minimum version the plugin supports.The registry mode in which it fetches the cluster's signing keys itself (discovery). I used static keys.Load on the registry itself: how it copes with hundreds of nodes asking for tokens at the same time. Code and Further Reading The kubelet side is described in the Kubernetes documentation on kubelet credential providers and in KEP-4412. The example plugin, the installation recipes, and all configs from this article are in the artifact-keeper-kubelet-provider repository. If you try the recipes on EKS, GKE, or AKS, a note about what worked and what did not is welcome.
The thought of granting AI agent permissions to work on your AWS setup might seem scary and dangerous to some and very alluring to others. Traditionally, scripts or predefined sets of actions were used in specific scenarios. Now AI has “reasoning”; whether good or bad, its scope of action might go way beyond scripted limits. It is called AI blast: the number of decisions the agent can make before someone stops it. What Can Go Wrong? There are several things that can go wrong. Let's take a look at some of the critical things that can go wrong. Misdiagnosing the Problem The agent sees CPU utilization at 95% and decides to increase the instance size. But the real problem is a memory leak. The change may temporarily reduce the symptoms while increasing cost and leaving the underlying failure untouched. Cascading Changes One seemingly harmless change can trigger a chain reaction. An agent modifies a security group, which affects connectivity, which causes a deployment to fail, which then triggers another automated remediation. Each action may look reasonable, but the combined result is anything but. Wrong Cleanup of Volumes The agent identifies old EBS volumes, snapshots, or other resources as unused and deletes them. It cannot easily know that a volume may be intentionally detached, required for disaster recovery, or part of an undocumented operational procedure. Security Regression An agent trying to restore availability might weaken a security control to make a service work, for example, opening a port, broadening an IAM policy, or changing a network rule. The immediate incident gets resolved, but the environment is left in a less secure state. Prompt Injection One of the biggest threats for agentic systems. It’s the attack where malicious content in the agent’s environment, a document the agent is asked to process, a webpage it visits, or a tool result it receives, contains text designed to override the agent’s instructions and cause it to take unauthorized actions. In the context of identity and access management, the most dangerous variant targets credentials: a malicious prompt instructs the agent to exfiltrate credentials available in its execution environment. Let's consider a scenario where an agent notices an EC2 instance running at 95% CPU. It decides to scale the instance, modifies an Auto Scaling policy, changes a security group, and deletes an “unused” EBS volume. Some of these actions are reasonable except one. Deleting an EBS volume that is considered “unused” might cause an outage if the volume is actually attached or required by the instance or other services. Sometimes volumes appear unused but are critical for data or system operation. Now, a reasonable question: why would an agent that only needs to scale EC2 need permission to drop EBS? So, based on this, one might conclude that granting agents least-privilege access is the correct choice. What does least-privilege access mean for agents? Impersonation vs. Delegation First, let's distinguish between two ways agents can work in your setup. First is impersonation; in this case, the agent performs tasks on the user's behalf, presenting itself as the user. Well, this is also an option, but not the right choice. Maintaining clear attribution and continuously monitoring activity is particularly important in environments subject to frameworks such as SOC 2. Auditing will fail; logs won’t allow us to figure out which actions were performed by the user and which by the agent. In this case, it would be impossible to tailor permissions at the agent level. The other option is delegation, and it is best practice because, in this case, we can give agents a scope of permissions beyond which they won’t act. Now, how do we decide on the right scope of permissions for agents? All permissions need to be carefully classified. Having one agent in your setup with a full assistant role won’t be the right choice. It would require giving all permissions at once, which contradicts the least-privilege principle. At this stage, agents need to be subdivided into sub-agents. Some agents need to read only; others diagnose and recommend. Other agents need to restart instances; some create or delete resources; some change policies or modify networking; some can execute (and here we need to be careful; there is a difference between prod and dev environments); and, most importantly, choose which agents can delete resources and modify policies. Each permission is tailored to perform the exact task the agent must complete. On top of these small, specialized agents sits the orchestration agent, which controls the workflow for the user. It will not have permissions exceeding the user's permissions and additional limitations based on its role and workflows. The orchestrator role needs permission to run Lambda functions, start Step Functions, manage workflow data in DynamoDB, and send approval messages through SNS. It does not need permissions for EKS, ECR, or AWS CloudFormation; those are for the deployment agent’s role. The deployment agent needs permissions for EKS and ECR but doesn’t need the wide Lambda permissions that the orchestrator requires. On top of this will be users who will act as the base and initiators of all the models. In a mature system, users will also be involved in the agentic system workflow, not step aside and leave all the work for agents. When agent changes are low risk, they might auto-execute. When risks are higher, you might need to add user approval before execution. Approval gates Final Thoughts Overall, the answer is not to deny agents from taking actions, but to ensure every action is within the right scope of permissions. The ultimate question is how many permissions should be granted to agentic systems and under what conditions. Delegation, least privilege, task-specific permissions, and human approval gates are the right way to achieve systems that will not damage your AWS environment. The more tasks we delegate to AI agents, the more carefully we should design the boundaries within which they need to operate.
Integration testing is the backbone of reliable data-driven Java applications. When working with relational databases in the Spring ecosystem, setting up test data per test method is effortless thanks to the org.springframework.test.context.jdbc.Sql annotation. However, once you move to MongoDB, you quickly notice a gap. Spinning up a real MongoDB instance for tests is easier than ever — whether you use Testcontainers with the official MongoDB Java Driver or Embedded MongoDB in Spring Boot — but Spring Data MongoDB does not provide a built-in equivalent to the @Sql annotation for declaratively seeding collections, cleaning up data, or managing indexes before each test. In this article, we will look at why @Sql is so productive for relational databases, compare four practical approaches for seeding and managing MongoDB state in Java integration tests, using Flyway or Liquibase libraries, and also explore how the junit5-mongo-extension library brings a true @Sql-like experience. The Gold Standard in Relational Testing: Spring's @Sql Annotation In Spring integration tests backed by SQL databases, the Sql annotation lets you declaratively execute SQL scripts before or after a test class or test method: Java package com.example.demo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.jdbc.Sql.ExecutionPhase; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @DataJpaTest class UserSqlRepositoryTest { @Autowired private UserRepository userRepository; @Test @Sql(scripts = {"/sql/clear_users.sql", "/sql/insert_active_users.sql"}, executionPhase = ExecutionPhase.BEFORE_TEST_METHOD) void shouldFindActiveUsers() { List<User> activeUsers = userRepository.findByActiveTrue(); assertThat(activeUsers).hasSize(3); } } What makes the Sql annotation so developer-friendly? Declarative and self-documenting: Looking at the test method immediately tells you what data preconditions apply.Per-test isolation: Different test methods in the same class can load completely different datasets or schema tweaks.Zero boilerplate: No manual file reading, JSON/SQL parsing, or lifecycle hook plumbing in your test classes. Current Testing Solutions for MongoDB When working with MongoDB and testing complex aggregation pipelines or full-text search, we need the same level of control over documents and MongoDB Atlas indexes. Yet out of the box, there is no @MongoSql or @MongoData annotation in Spring. Available Alternatives for Testing Integration With MongoDB in Java Although there is no annotation implemented yet that makes testing really user-friendly in Spring for MongoDB, there are a couple of approaches that could be used as alternatives to fill this gap. Option A: Programmatic Seeding With MongoTemplate and Jackson (@BeforeEach) The most common approach in Spring Boot applications is reading JSON files from the classpath and inserting them programmatically inside JUnit 5's @BeforeEach lifecycle method using MongoTemplate and Jackson's ObjectMapper. Java @DataMongoTest class UserRepositoryTest { @Autowired private MongoTemplate mongoTemplate; @Autowired private ObjectMapper objectMapper; @BeforeEach void setUp() throws Exception { // Clear collection mongoTemplate.dropCollection(User.class); // Load JSON dataset from test resources List<User> users = objectMapper.readValue( new ClassPathResource("data/users.json").getInputStream(), new TypeReference<List<User>>() {} ); // Insert into MongoDB mongoTemplate.insert(users, User.class); } @Test void testFindUser() { // Test logic here... } } Pros: No extra libraries required beyond Spring Boot starter dependencies.Full programmatic flexibility in Java. Cons: Repetitive boilerplate: Every test class needs resource loading and cleanup code.Poor per-method granularity:@BeforeEach runs the same setup for every test in the class. If different tests require different JSON files or index configurations, you end up calling helper methods inside every @Test method.Type coupling: Using Jackson, the ObjectMapper ties the JSON format to your Java entity mapping rather than MongoDB Extended JSON/raw BSON types (such as ObjectId, ISODate, or Decimal128). Option B: Custom Annotation + Spring TestExecutionListener If you want a declarative syntax similar to the @Sql (for example, @MongoDataSet("/data/users.json")), you can build a custom annotation paired with a Spring TestExecutionListener. First, define the Annotation. Java @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface MongoDataSet { String[] value(); // Paths to JSON files on the classpath String collection(); } Then implement the TestExecutionListener. Java public class MongoDataSetTestExecutionListener extends AbstractTestExecutionListener { @Override public void beforeTestMethod(TestContext testContext) throws Exception { MongoDataSet annotation = AnnotatedElementUtils.findMergedAnnotation( testContext.getTestMethod(), MongoDataSet.class); if (annotation == null) { annotation = AnnotatedElementUtils.findMergedAnnotation( testContext.getTestClass(), MongoDataSet.class); } if (annotation != null) { MongoTemplate mongoTemplate = testContext.getApplicationContext() .getBean(MongoTemplate.class); mongoTemplate.dropCollection(annotation.collection()); for (String path : annotation.value()) { String json = StreamUtils.copyToString( new ClassPathResource(path).getInputStream(), StandardCharsets.UTF_8); Document doc = Document.parse(json); mongoTemplate.insert(doc, annotation.collection()); } } } } Pros: Declarative and tailored to your exact project needs.Keeps test classes clean. Cons: You own the maintenance: As soon as you need JSON arrays vs. single documents, multiple collections per test, write concerns, batch inserts, standard index creation, or Atlas Search index readiness checks, your "simple" listener grows into a custom framework that you have to test and maintain yourself. Option C: Testcontainers + Migration Tools (Flyway/Liquibase) When your integration tests spin up ephemeral databases using Testcontainers (or Quarkus DevServices), another common enterprise pattern is combining containers with database migration tools such as Liquibase (via the Liquibase MongoDB extension) or Flyway (which supports MongoDB migrations in recent versions): With this approach, you have to follow these steps: Spin up a MongoDBContainer (Embedded is also a good alternative) or MongoDBAtlasLocalContainer.Let Liquibase or Flyway automatically execute migration scripts on startup to create collections, validation rules, and baseline indexes.Use a JUnit 5 callback or utility helper to clean or seed collections between tests if strict isolation is required. Pros: Production parity: Verifies that your production migration scripts and baseline indexes work against a real MongoDB instance. Cons: Not designed for per-test variations: Migration tools are forward-only and version-controlled for application startup, not for switching datasets or testing different index combinations on a method-by-method basis. Option D: Declarative Setup With junit5-mongo-extension Library If you are looking for the closest equivalent to Spring's @Sql for MongoDB—without writing and maintaining custom plumbing, the junit5-mongo-extension sublibrary from the Jamolingo project is purpose-built for this scenario. Originally created to support extensive integration for Jamolingo (check an OData-to-MongoDB query translator), the junit5-mongo-extension is a lightweight, standalone JUnit 5 extension family with three modules: junit5-mongo-extension – Environment-agnostic core (works with any Java framework by extending AbstractMongoDataLoaderExtension).junit5-mongo-extension-spring – Ready-to-use Spring/Spring Boot extension (SpringMongoDataLoaderExtension) that automatically resolves MongoClient from the Spring ApplicationContext.junit5-mongo-extension-quarkus – Ready-to-use Quarkus extension (QuarkusMongoDataLoaderExtension) that resolves MongoClient from the Quarkus Arc container. To use the jamolingo extension, you have to: Add the dependency (Spring Boot example with Maven as a build tool). XML <dependency> <groupId>com.github.starnowski.jamolingo</groupId> <artifactId>junit5-mongo-extension-spring</artifactId> <version>0.10.0</version> <scope>test</scope> </dependency> 1. Inserting Documents and Clearing Collections Using the @MongoSetup and @MongoDocument, you can specify which collections to populate before a test class or test method runs. Each bsonFilePath can point to either a single BSON/JSON document ({...}) or a JSON array of documents ([{...}, {...}]), supporting full MongoDB Extended JSON syntax. Java import com.github.starnowski.jamolingo.junit5.MongoDocument; import com.github.starnowski.jamolingo.junit5.MongoSetup; import com.github.starnowski.jamolingo.junit5.SpringMongoDataLoaderExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest @ExtendWith(SpringMongoDataLoaderExtension.class) class OrderIntegrationTest { @Test @MongoSetup( batchInsertToCollection = true, mongoDocuments = { // Inserts an array or single document from classpath; clears "users" first @MongoDocument( database = "shop_db", collection = "users", bsonFilePath = "data/users.json" ), // Multiple files can be loaded into the same collection @MongoDocument( database = "shop_db", collection = "orders", bsonFilePath = "data/active_orders.json" ), @MongoDocument( database = "shop_db", collection = "orders", bsonFilePath = "data/archived_orders.json" ), // Leaving bsonFilePath empty explicitly erases the "audit_logs" collection! @MongoDocument( database = "shop_db", collection = "audit_logs" ) } ) void shouldProcessUserOrdersWithCleanAuditLog() { // 1. "users", "orders", and "audit_logs" collections were automatically cleared once. // 2. "users" and "orders" were populated in batch mode (insertMany). // 3. "audit_logs" is guaranteed to be empty. } } Key behaviors: Automatic cleanup: Before inserting documents into a target collection, the extension automatically clears existing documents in that collection (deleteMany(new Document())).Explicit collection clearing: If you leave bsonFilePath empty (the default), the extension simply clears that collection without inserting anything.Multiple files per collection: If you list multiple @MongoDocument entries for the same collection, the collection is cleared only once at the beginning of setup, and then all specified files are inserted. 2. Managing and Synchronizing MongoDB Atlas Search Indexes Testing MongoDB Atlas Search ($search and $searchMeta aggregation stages) locally with the mongodb/mongodb-atlas-local Docker image in Testcontainers introduces a notorious challenge (Atlas Search indexes are built and updated asynchronously in the background). If you insert documents and immediately run a $search query in your test, the test will randomly fail because the Lucene-based Atlas Search index hasn't finished indexing the newly inserted documents yet. The junit5-mongo-extension solves this with the @AtlasSearchIndex and the @AtlasSearchIndexValidation: Java @SpringBootTest @ExtendWith(SpringMongoDataLoaderExtension.class) @AtlasSearchIndexValidation( maxWaitDuration = 45, maxWaitUnit = TimeUnit.SECONDS, pollInterval = 500, pollIntervalUnit = TimeUnit.MILLISECONDS ) class AtlasSearchIntegrationTest { @Test @MongoSetup( mongoDocuments = { @MongoDocument( database = "test_db", collection = "items", bsonFilePath = "data/items.json" ) }, atlasSearchIndexes = { @AtlasSearchIndex( name = "default", database = "test_db", collection = "items", bsonFilePath = "search/items_search_index.json", validationProperty = {"name", "description"} ) } ) void shouldFindItemsUsingAtlasSearch() { // At this point: // 1. "items" collection is cleared and populated. // 2. The "default" Atlas Search index is created (or replaced if its JSON definition changed). // 3. The extension has waited until the index is READY and all documents' "name" and "description" // fields are searchable! } } Where search/items_search_index.json defines your Atlas Search mappings and analyzers: JSON { "mappings": { "dynamic": false, "fields": { "name": [ { "type": "string" } ], "description": [ { "type": "string" } ] } } } Behind the scenes, the @AtlasSearchIndex handles the entire lifecycle: Creation, modification, and caching: It checks whether the target search index already exists and matches the cached JSON definition. If the index doesn't exist, it creates it. If a test uses a different bsonFilePath (modifying the index definition), the extension drops the old search index, waits until it is removed, and creates the new one.Multi-stage synchronization validation: After inserting documents, it runs a pipeline of validation strategies (customizable via validationStrategies): AtlasSearchIndexReadinessSyncValidationStrategy – Polls until the Atlas Search index status reaches "READY".AtlasSearchIndexDocumentCountSyncValidationStrategy – Polls $searchMeta until the indexed document count for each validationProperty matches the actual collection document count.AtlasSearchIndexValuesSyncValidationStrategy – Executes $search queries for the actual values of validationProperty in your inserted documents until the expected document _ids are returned. Practical Recommendations: Which One Should You Choose? 1. Programmatic Seeding (@BeforeEach) or a Custom Implementation (Options A–B) Choose Option A if you have a small microservice with only a handful of simple repository tests, where every test shares the exact same dataset, and you want zero extra test dependencies.Choose Option B only if your organization has strict policies against third-party test libraries or requires tightly coupled custom logic (such as encrypting fields via an internal KMS during test data loading). 2. Flyway or Liquibase (Option C) Use Liquibase or Flyway alongside Testcontainers to apply your application-wide baseline migrations (creating collections, JSON schema validators, production indexes, and static dictionary data) when the test container starts up.Think of Flyway/Liquibase as the MongoDB equivalent of running your production DDL migrations before the test suite starts — not as a replacement for per-test data seeding. 3. Jamolingo's junit5-mongo-extension (Option D) Choose junit5-mongo-extension whenever you want the productivity of Spring's @Sql in MongoDB integration tests.It is the ideal choice when different test methods need different document sets, when you need to declaratively clear collections, when you test index-sensitive queries, or when you test MongoDB Atlas Search and need deterministic index synchronization without flaky tests.Best of all, you can combine Option C and Option E: let Liquibase/Flyway verify your baseline migrations on container startup, and use @MongoSetup on your test methods to seed test-specific documents and indexes!
A wire-level comparison of function definitions, Call IDs, result messages, streaming arguments, authorization, idempotency, and route compatibility. Responses and Chat Completions can both ask an application to run a function, but they represent the tool loop differently. Chat Completions puts tool definitions under tools[].function, returns message.tool_calls, and accepts results as role: "tool" messages. Responses uses flat function definitions, returns typed function_call output items, and accepts function_call_output items linked by call_id. The model does not execute your application function. Your code must validate the proposed arguments, authorize the operation, execute it exactly as intended, return a result to the model, and prevent duplicate side effects when a request is retried. The Tool Loop Has Four Steps The endpoint-specific JSON differs, but the application state machine is the same: Plain Text 1. Declare an allowed function and its argument schema 2. Receive one or more model-proposed function calls 3. Validate, authorize, and execute each call in application code 4. Return each result using the call's correlation ID Only after step four can the model produce an answer grounded in the tool result. If the model requests another tool, the loop repeats with a new call ID. The OpenAI Function Calling guide describes this as a multi-step exchange. Treating the first tool call as a final answer is a common integration error. Compare the Wire Contracts The main differences are structural rather than conceptual. ConcernResponses APIChat CompletionsFunction definitionFlat tools[] item with name, description, parameters, stricttools[] item with those fields nested under functionModel-proposed callTyped function_call output itemAssistant message tool_calls[] entryCorrelation identifiercall_idTool call id, returned as tool_call_idFunction namefunction_call.nametool_calls[].function.nameArgumentsJSON string in function_call.argumentsJSON string in tool_calls[].function.argumentsTool resultfunction_call_output input itemMessage with role: "tool"Common streamed argumentsTyped function-argument delta eventsIndexed delta.tool_calls[] fragmentsFinal textTyped output items and output-text helperschoices[0].message.content Do not correlate calls by array position. Parallel calls and streamed chunks can arrive in an order that differs from the order in which your application finishes. The explicit call ID is the stable join key. Define One Strict Function Schema The following examples expose a read-only get_delivery_status function. The model may request an order status, but it cannot change an order, issue a refund, or access arbitrary storage. The argument schema is deliberately narrow: JSON { "type": "object", "properties": { "order_id": { "type": "string", "pattern": "^ORDER-[0-9]{4}$" } }, "required": [ "order_id" ], "additionalProperties": false } strict: true asks the supported model to adhere to the function argument schema. The application must still parse and validate the JSON before execution. Pattern support and other JSON Schema features can vary by model or provider, so the same compatibility gate used for Structured Outputs also applies to function arguments. Implement the Loop With the Responses API This JavaScript example keeps the exchange stateless by returning the model’s output items with the function result. It uses a deterministic local function so the control flow is visible without introducing another external API. JavaScript import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); const model = process.env.MODEL_ID; if (!model) throw new Error("MODEL_ID is required"); const orders = new Map([ ["ORDER-1001", { status: "in_transit", eta: "2026-08-06" }], ]); const tools = [ { type: "function", name: "get_delivery_status", description: "Return the current delivery status for one order.", parameters: { type: "object", properties: { order_id: { type: "string", pattern: "^ORDER-[0-9]{4}$" }, }, required: ["order_id"], additionalProperties: false, }, strict: true, }, ]; function executeTool(name, rawArguments) { if (name !== "get_delivery_status") { throw new Error(`Tool is not allowed: ${name}`); } const args = JSON.parse(rawArguments); if (!/^ORDER-[0-9]{4}$/.test(args.order_id)) { throw new Error("Invalid order_id"); } return orders.get(args.order_id) ?? { status: "not_found" }; } const first = await client.responses.create({ model, input: "Where is ORDER-1001?", tools, parallel_tool_calls: false, }); const calls = first.output.filter((item) => item.type === "function_call"); if (calls.length === 0) { console.log(first.output_text); process.exit(0); } const toolOutputs = calls.map((call) => ({ type: "function_call_output", call_id: call.call_id, output: JSON.stringify(executeTool(call.name, call.arguments)), })); const final = await client.responses.create({ model, input: [...first.output, ...toolOutputs], tools, parallel_tool_calls: false, }); console.log(final.output_text); For a stateful integration, Responses also supports continuing from a prior response where the route and storage policy permit it. A stateless example makes the complete transcript explicit and avoids assuming that every OpenAI-compatible route stores response state. The critical fields are call.call_id on the model output and the matching call_id on function_call_output. Returning a result with the wrong ID disconnects the data from the model’s request. Implement the Loop With Chat Completions The same application function can be used with Chat Completions. The tool definition and result message use the Chat wrapper. JavaScript import OpenAI from "openai"; const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, }); const model = process.env.MODEL_ID; if (!model) throw new Error("MODEL_ID is required"); const orders = new Map([ ["ORDER-1001", { status: "in_transit", eta: "2026-08-06" }], ]); const tools = [ { type: "function", function: { name: "get_delivery_status", description: "Return the current delivery status for one order.", parameters: { type: "object", properties: { order_id: { type: "string", pattern: "^ORDER-[0-9]{4}$" }, }, required: ["order_id"], additionalProperties: false, }, strict: true, }, }, ]; function executeTool(name, rawArguments) { if (name !== "get_delivery_status") { throw new Error(`Tool is not allowed: ${name}`); } const args = JSON.parse(rawArguments); if (!/^ORDER-[0-9]{4}$/.test(args.order_id)) { throw new Error("Invalid order_id"); } return orders.get(args.order_id) ?? { status: "not_found" }; } const messages = [ { role: "user", content: "Where is ORDER-1001?" }, ]; const first = await client.chat.completions.create({ model, messages, tools, parallel_tool_calls: false, }); const assistant = first.choices[0].message; const calls = assistant.tool_calls ?? []; if (calls.length === 0) { console.log(assistant.content); process.exit(0); } messages.push(assistant); for (const call of calls) { const result = executeTool(call.function.name, call.function.arguments); messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result), }); } const final = await client.chat.completions.create({ model, messages, tools, parallel_tool_calls: false, }); console.log(final.choices[0].message.content); Here, the first assistant message must be appended to messages before its tool results. Each result uses tool_call_id: call.id. Omitting the assistant tool-call message or returning an unmatched ID produces an invalid conversation history. Stream Arguments as Fragments, Not Complete JSON In streaming mode, function arguments can arrive in fragments. A chunk that contains {"order is not invalid JSON; it is incomplete JSON. The safe parser keeps one buffer per call identity: identify the call or indexed call slot from the event;append each argument delta to that call’s buffer;wait for the endpoint’s argument-done or completed signal;parse the complete string once;validate and execute only after completion. Responses uses typed events for function-call arguments and output items. Chat Completions emits fragments in choices[].delta.tool_calls[], where the index identifies the in-progress entry and the final tool call carries its stable ID. Do not execute a function when the first fragment arrives. The AI API Streaming Guide explains why connection, first event, first effective output, idle timeout, and completion should be measured separately. Make Tool Execution Safe and Idempotent Strict arguments improve structure, not authorization. Before executing any call: Allow only registered function names;Parse arguments with a size limit;Validate the complete schema in application code;Authorize the current user or workload for the requested resource;Separate read-only tools from tools with side effects;Redact secrets and sensitive output before returning it to the model;Use a deadline and bounded downstream retries;Record a safe operation reference, not raw secrets or private content. For a side-effecting tool, use an idempotency key derived from a stable application request and call identity. Store the completed result before returning it to the model. If a network retry replays the same call, return the stored result rather than issuing a second refund, message, deployment, or database mutation. The model-generated function name and arguments are untrusted input. A valid schema cannot grant permission, prove ownership, or replace a transaction boundary. Decide How to Handle Multiple Calls The examples set parallel_tool_calls: false to keep the state machine easy to inspect. If parallel calls are enabled: Correlate every result by call ID, never by completion order;Enforce a maximum number of calls per response;Apply a concurrency limit in the application;Define whether one failed tool cancels, blocks, or coexists with successful tools;Return one result for every accepted call;Keep side-effecting operations serialized when their order matters. Parallel execution can reduce latency for independent reads, but it increases authorization, ordering, retry, and partial-failure complexity. Enable it because the workload benefits, not because the parameter exists. Choose the Format by the Application Contract Use Responses when the application benefits from typed output items, the Responses event model, state-continuation options, or other verified Responses capabilities. Use Chat Completions when the application already owns a stable message transcript and the selected provider’s tool contract is verified. The broader endpoint decision is covered in Responses API vs Chat Completions. The implementation standard should be the same in both cases: explicit tool allowlists, strict argument schemas, application-side validation, authorization before execution, correlation by call ID, idempotency for side effects, and a complete result returned to the model. Those controls—not the endpoint name—make a function-calling workflow reliable.
Principal PM, Azure Cosmos DB,
Microsoft
Cloud Ops DBA,
Allspring
Award-winning Software Engineer and Architect,
OS Expert