SHEET 03blog/singleton-cron-runs-everywhere/ REVISED 

Your "singleton" cron runs on every server

A nightly expiry job ran on every autoscaling instance and expired 94 gift cards twice. What fixed it, and why a time window can't tell a retry from a real repeat.

Published
Length
7 min read

When an app moves from one server to an autoscaling group, a cron job that used to run once can end up running on every instance. Jobs written on the assumption that only one copy runs start racing themselves. On a client’s gift-card and voucher platform, that expired 94 cards twice, 11 seconds apart, and had two copies of a rebuild job wiping each other’s working data. The fixes were a per-item lock with a re-read inside it, a single-flight lock for the rebuild, and a session-local temporary table. Under all of it was a duplicate check that only matched rows written in the same second, and the same weakness let card claims go through two or three times. That last one needs an idempotency key, because a time window can’t tell a retry from a real repeat.

What broke

The platform has a nightly integrity check. For every card it compares the balance on the card’s own row with a balance rebuilt by replaying the card’s status history: created, paid, claimed, expired and so on. One morning it flagged 94 cards with impossible history. A typical one read 0 on the card and −300 from the replay.

That card’s history explained it:

Status When (UTC)
Created 2023-07-02 09:04:43
Paid 2023-07-02 09:06:37
Expired 2026-07-03 02:33:15
Expired 2026-07-03 02:33:26

It had been expired twice, 11 seconds apart, on the same night, and both Expired rows came from the cron. The replay comes to +300 for paid, minus 300 twice for the two expiries, which is −300. The card itself correctly says 0.

Root cause

The expiry job ran on every instance in the autoscaling group, and there were two overnight. Both fetched the same list of paid cards that had passed their validity date. Both wrote an Expired row for each.

There was a duplicate guard. It checked whether an identical status row already existed, but only within the same clock second. Two servers 11 seconds apart went straight through it. There was no unique constraint and no lock.

That also explained a detail in the alert. It printed suggested cleanup SQL for each kind of duplicate. The section for user-driven claims was empty and the section for cron-driven expiry was full. All of these duplicates came from the expiry job.

The fix for the expiry job

A short per-item MySQL advisory lock, and a re-read of the status inside it:

if (!$this->acquireExpiryLock($name)) {   // SELECT GET_LOCK(:name, 5) = 1
    return false;                          // fail closed: skip, next run picks it up
}
try {
    if (!$this->refresh()) return false;   // re-read; our copy may be stale
    if ($this->status === PAID && !$this->isValid()) {
        $this->setStatus(EXPIRED);
        return true;
    }
    return false;
} finally {
    $this->releaseExpiryLock($name);
}

The second runner blocks on the lock, then re-reads the card, sees it’s already expired, and does nothing. The re-read is the important half. Without it, the second runner would wait politely for the lock and then write the duplicate anyway, from the stale copy it loaded before.

It fails closed. If the lock isn’t definitely held, because another instance has it or the lock call errored, the job skips the card. Skipping costs nothing: the card is either being expired right now or will be on the next run. Guessing wrong writes another bad ledger row.

The method is shared by all item types, so they all got the fix. It also covers pages that expire a card on demand when it’s viewed, which could race the cron too.

The alert’s own cleanup SQL was wrong

While checking the 94 cards, I found a bug in the integrity check’s suggested cleanup. It collapsed runs of consecutive identical statuses, but it only flushed the last run. A card that was expired twice, reactivated, and later expired again would only have its final duplicate removed. The earlier one stayed, and the suggested DELETE statements quietly under-deleted. I pulled that logic into a pure function with tests, including the case that used to fail.

The repair for the 94 cards was planned to run only after the fix was live, dry run first, so the next night’s run couldn’t dirty them again.

Two copies of a rebuild, one scratch table

A different job had the same root cause and a nastier symptom. A bookkeeping rebuild staged row ids in a shared table, tmp_id, with TRUNCATE then INSERT, before rewriting payment lines from it. With two instances, one run’s TRUNCATE wiped the other’s staged ids mid-flight. That gave 1213 deadlocks and could leave wrong or duplicated payment lines.

The first fix was a single-flight named lock:

SELECT GET_LOCK('cron:bookkeeper-payment-lines', 0);  -- 0 = don't wait
-- ... rebuild ...
SELECT RELEASE_LOCK('cron:bookkeeper-payment-lines');  -- in finally

It’s non-blocking on purpose. The rebuild is idempotent, so if another run holds the lock, this one skips and the holder or the next scheduled run covers it. A blocking wait could also push callers past their 60-second set_time_limit.

But the lock only covered the cron’s callers. Three payout buttons in the admin panel also wrote to tmp_id, and they weren’t behind it. The structural fix was to make the scratch table private to each connection:

CREATE TEMPORARY TABLE IF NOT EXISTS tmp_id (id BIGINT NOT NULL PRIMARY KEY) ENGINE=InnoDB;
TRUNCATE TABLE tmp_id;

A TEMPORARY table exists only for the session that created it, so no writer can touch another’s rows, and that holds with no lock at all. I added that one line before each of the six TRUNCATEs and left every money statement byte-identical. The test opens two real connections and checks that one TRUNCATE no longer empties the other’s table.

Why a time window can’t dedupe a retry

The same-second guard had a second victim. Some cards were claimed two or three times, 1 to 13 seconds apart. The causes were point-of-sale double-taps, retries and concurrent submits. A card’s balance is its amount minus the sum of its claim rows, so a duplicate row is the bug.

The obvious fix is a wider window, so I tried one: 90 seconds. Review found it dropped real work. The duplicate check was shared by every status change, so legitimate repeat refunds were dropped, and so were claims, while the screen still reported success. I moved the wider check into a claim-only path, but the underlying problem stayed.

A window compares content and time. Two claims of the same amount on the same card a few seconds apart look identical whether they’re one tap sent twice or two real purchases. Make the window wide enough to catch retries, and it blocks real repeats. Make it narrow enough to allow repeats, and retries slip through. No width gets both right.

What can tell them apart is operation identity. The design I wrote for claims:

  • The client sends an idempotency key: a hidden per-render token on operator forms, and an Idempotency-Key header on the public API.
  • The claim tables get a nullable idempotency_key with UNIQUE (item_id, idempotency_key). MySQL allows many NULLs in a unique index, so old rows and keyless callers need no backfill.
  • The balance decrement and the claim row go in one transaction. A duplicate key fails on the index, rolls the whole thing back, and returns the original result: “already registered”.
  • A distinct key goes through, so two real identical claims both work.
  • Submit buttons disable on click, so most double-taps never reach the server.

That change is written and reviewed but hadn’t merged when I wrote this, so I won’t claim results for it. A related fix on the payment side did ship. A payment callback that failed halfway had already written its Paid row, and the gateway’s redelivery 90 seconds later wrote a second one, because the same-second guard couldn’t see it. Now the paid transition runs in one transaction under a row lock (SELECT ... FOR UPDATE) and skips only when the card already has the paid status and its history already has the row. A callback that can’t get the lock in time answers 503, and the gateway delivers it again later.

What to check in your own system

  • List every cron job and ask what happens if two copies run at once, a few seconds apart. Then check how many copies actually run.
  • Look for shared “scratch” tables that get truncated and refilled. Make them session-local temporary tables, or put a lock around every writer, not only the cron.
  • When you add a lock, re-read the state inside it. Holding a lock while acting on data you read before you took it doesn’t help.
  • Search for duplicate checks based on time: “same second”, “within N seconds”, “created in the last minute”. Each one either misses retries or blocks real repeats. If the operation moves money, give it an identity and let a unique constraint enforce it.

The lock problems behind a different cron on the same database are in One DATE() call was locking 1.4 million rows every five minutes.

About the author

Software engineer and serial founder in Alexandria, Egypt, and CTO at Zaher.AI, a GEO and SEO agency serving MENA.

Console

Type help and press Enter.