Dev.to Security 🔐 Cybersecurity 👁 2 📖 9 min read

Make a 2Captcha Balance Import Safe to Replay After a Worker Restarts

An authorized account observation from a workflow around 2Captcha can reach an internal report more than once if an importing worker restarts. This case puts the replay policy at the receiving table. The SQLite fixture u

Make a 2Captcha Balance Import Safe to Replay After a Worker Restarts

An authorized account observation from a workflow around 2Captcha can reach an internal report more than once if an importing worker restarts. This case puts the replay policy at the receiving table. The SQLite fixture uses invented identifiers and amounts and exercises an interrupted transaction, a repeated delivery and a conflicting copy.

Replay one balance observation and verify its durable key

Choose a stable observation identity

The receiver needs to know which event an incoming row represents. A local sequence generated by the worker gets a new value after a restart. If the permitted source supplies a durable observation ID, carry it alongside the account alias and source scope. Otherwise define and test a durable import key at the point where the business record is first created. Record how the key was obtained so an independent reviewer can reconstruct it.

A balance is a point-in-time observation. Two independently captured readings can legitimately have the same amount and currency. Keep them separate under their own IDs. Deduplicating by amount can create gaps in visibility. Conversely a retry of one observation can produce two arrivals with different received timestamps, so the receiver needs a record of the source event and an independent record of delivery history.

Commit the accepted record as one operation

Place a database constraint on the exact identity tuple. Decide how an already-present row is classified before recording an acknowledgement that tells the worker it may move on. A read-modify-write sequence spread across separate transactions can leave a gap in which a second writer makes a conflicting insertion. The sample uses a write transaction and restricts the decision to one source observation.

Acknowledge a successful result after the transaction commits. If a worker dies after commit and before acknowledgement, the next delivery finds its existing record and returns the replay outcome. If a worker dies before commit, the original attempt can be retried normally. Keeping the verified source row after either interruption matters more than trying to force timing in a production test.

Run the synthetic fixture

This runnable in-memory SQLite fixture uses a unique compound key and a transactional decision. Each API-independent sample uses cents. An interrupted transaction is modeled by raising an exception before commit. The exception does not stand in for a provider error.

import sqlite3
db = sqlite3.connect(":memory:", isolation_level=None)
db.execute("CREATE TABLE observations (account TEXT, event TEXT, cents INTEGER, PRIMARY KEY(account, event))")

def receive(account, event, cents, *, interrupt=False):
    db.execute("BEGIN IMMEDIATE")
    try:
        row = db.execute("SELECT cents FROM observations WHERE account = ? AND event = ?", (account, event)).fetchone()
        if row is None:
            db.execute("INSERT INTO observations VALUES (?, ?, ?)", (account, event, cents))
            outcome = "inserted"
        else:
            outcome = "replayed" if row[0] == cents else "conflict"
        if interrupt:
            raise RuntimeError("synthetic worker stops")
        db.execute("COMMIT")
    except Exception:
        db.execute("ROLLBACK")
        raise
    return outcome

try:
    receive("qa", "E1", 400, interrupt=True)
except RuntimeError:
    print("first insert rolled back")
for amount, expected in [(400, "inserted"), (400, "replayed"), (420, "conflict")]:
    result = receive("qa", "E1", amount)
    assert result == expected
    print(result)
assert db.execute("SELECT * FROM observations").fetchall() == [("qa", "E1", 400)]
print("rows kept: 1")
first insert rolled back
inserted
replayed
conflict
rows kept: 1

The local transaction rolls back once. A successful retry stores one record, a byte-for-business-equivalent replay leaves it alone, and a changed copy becomes a conflict. The stored observation remains at 400 cents. An application can route the conflict to its internal owner without changing the accepted row.

Review the boundary cases

Stop before the commit. Interrupt the write transaction after the insert attempt. The expected result is a rolled-back write that can be retried. The source event does not become partially accepted.

Repeat after commit. Deliver the same key and amount with a new arrival timestamp. The expected result is one accepted observation and a replay disposition. A transport retry leaves the business count stable.

Change an accepted value. Deliver the same identity with a different amount. The expected result is conflict with the original kept. A legitimate correction will need its own evidence and approval.

Keep account scope. Reuse the fictional event ID under another authorized account alias. The expected result is independent identity under the declared key. The key records which scope owns the observation.

Send a changed copy to the right owner

An already used ID with a different amount is evidence of disagreement between deliveries. The receiving report can preserve the first reviewed reading and write a bounded reason to a review queue. A permitted correction should carry an independent revision reference and a choice about which view applies. An import that silently overwrites each version can make an earlier internal statement impossible to reproduce.

The comparison also includes currency and the represented observation time where the source contract requires it. The fixture uses integer minor units and one currency across the simple amount test. Document which fields are part of the replay equivalence rule. Metadata such as received time and worker ID may still be retained for an operator without changing what the underlying financial observation represents.

Rehearse crash boundaries with an actual report path

Run one example that rolls back before commit and a second that delivers an already committed observation again. Ask a report owner to compare the stored rows and the recorded dispositions. The passing result for replay has exactly one accepted row with its original evidence. A conflicting copy has a named reason and an accessible route to the reviewer who owns the import contract.

If a receiving system also advances a producer checkpoint, commit the checkpoint with the accepted batch where feasible or make its separate update retryable. Replaying a batch whose imported records already exist should not inflate the number of observations. Put a limit on the amount of evidence in alerts. The reviewer can follow normal account permissions to see source details when further investigation is necessary.

At deployment time preserve the old observation history during a dry run. Compare expected records by identity and not only a balance summary. If a unique key needs backfilling, start with one bounded account and investigate collisions before enforcing it. Define how to report deliveries that cannot establish a stable key. An unknown ID policy is essential when some earlier exports did not retain identity.

Keep the evidence with the decision

I would make the review packet small enough that the owner maintaining the balance import can read it without the development environment. Start with an approved local account feed and synthetic restart log. Put the rule and its version beside the inputs and name the comparison grain as one account alias and durable source observation ID. The reader should be able to mark each item independently with one disposition before looking at what the program did. Ask them to point to the field and source behind at least one accepted item. If they can only infer the rule from a convenient example, the packet is still missing an explicit assumption.

For each outcome in a committed source record and an equivalent replay, keep a bounded reference to the original evidence and the reason it passed. Give a reused identity with a conflicting amount a distinct disposition and a visible route for another review. That route should describe the missing information without implying that an unobserved event occurred. A report that silently drops unresolved rows can look unusually clean, and downstream counts can change after a reviewer supplies the missing evidence. Record which observations left the reviewed population and the rule that decides when they may re-enter it.

Use account alias, observation ID and disposition from the receiving transaction to confirm that an ordinary report can be reconstructed from a dated source. Keep a copy of the earlier rule when it is still used to interpret a previous report. A new decision should have its own effective date and evidence reference. Make an independent reviewer run the same small case, then ask them why the earlier and later outcomes differ. This will also show whether a changed summary was caused by a new input, an updated decision rule, or a change in formatting and labeling.

Decide where the data stops moving if a required part of an approved local account feed and synthetic restart log is unavailable. If the usual reader can use a prior validated output, give it a timestamp and label that output as the last valid observation. Send reviewers a short reason that identifies a reused identity with a conflicting amount within the scope of one account alias and durable source observation ID. Avoid putting a raw private record or secret into the report to make support easier. The normal access controls can retain those details while the handoff preserves enough information to reproduce the classification.

Exercise the handoff before depending on it

Give two people comparable copies of the fixture. Ask one to explain which conclusions the output supports and one to identify the first place a bad result becomes visible. Both should have the same definitions of a committed source record and an equivalent replay. Then replace only one record with an unresolved variant. A clear workflow can tell the user the item is waiting on evidence without giving it the same status as an established failure. Capture the wording and the first place in the process where the decision changes.

Check cases where the export itself is valid but the context is wrong. Use one complete example outside one account alias and durable source observation ID and see whether the routine workflow keeps it out of the result. Then change the input order and verify that the same report can still be reproduced. Where sequence is meaningful, record how it was established and add an explicit opposite-case test. An accidental dependence on an input file ordering can be difficult to notice when a successful run only shows final totals.

For the first real rollout, run the new check against one small approved sample and retain the earlier interpretation for comparison. Count the visible outcomes and sample one that changed and one that stayed the same. When the differences concern a reused identity with a conflicting amount, confirm what a reader would do next and which owner has the evidence needed to act. Leave the previous release available until the owner maintaining the balance import can explain any material differences that affect ordinary decisions.

Record one success criterion and one reason to stop the rollout before the first real run. A useful criterion names a committed source record and an equivalent replay and says who will verify it. A stop decision should identify whether the failure affects the whole report or only a documented subset. Keep the recorded disposition separate from the decision to review a new release. This protects a prior evidence packet while allowing the team to correct a rule that only appeared to work on a convenient sample.

Run the restart test before depending on the import

When integrating a permitted read-only workflow for 2Captcha, choose a stable source observation identity. Rehearse both a failed first delivery and a second delivery after commit. Give the report owner access to the conflict disposition and the rule that protects the first accepted reading.

Prepared with AI assistance. The code was run on local synthetic data. The example illustrates the reporting method. It makes no claim about measured service performance.

Further reading

Design an Internal 2Captcha Balance Status Page That Ages Gracefully describes how to use the last accepted observation after it is stored.

Match a 2Captcha Receipt to Exactly One Ledger Line shows another case that requires a durable source identifier.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.