Two workers took one job: lease, expiry, and fencing

A lease expires, but the old worker resumes. Using MySQL 8.4/InnoDB, we examine ownership generations, atomic result acceptance, and rejection of stale completion, renewal, and release.

Permission handed to another worker does not return with the old key.
Permission handed to another worker does not return with the old key.

Worker A has acquired a job and started preparing its result. Then it pauses for a long time: the process is alive, but no longer sends signals. The system stops waiting and hands the job to worker B. When A resumes, it still has the old input and believes the job belongs to it.

This is where the statement “we have a lock” needs a follow-up. Who may write the result after the handover? Can the old worker extend its permission? What happens if it tries to release a lock that now belongs to someone else?

It helps to separate three decisions: temporary permission to work, the generation of that permission, and final acceptance of a change by the storage system itself. The teaching model runs within one application on MySQL 8.4/InnoDB through native PDO. The following describes its contract and controlled call ordering; it does not test a distributed system or simultaneous execution by two OS processes.

Expiring permission does not stop a process

A lease grants permission to use a resource until a defined boundary. It lets the system hand work to another worker when the first stops responding. Expiry does not remove the old process from memory or cancel a command it has already prepared.

The Symfony Lock documentation describes this property of expiring stores explicitly: another process may acquire the lock after its TTL ends. refresh() helps maintain a valid claim during long work, but losing the lock requires explicit handling.

A check before computation is useful, yet a pause may occur between that check and the write. A checks its permission, pauses, B acquires a new claim, and A wakes up and submits the old result. Another check held only in A’s memory does not change this event order.

A longer TTL reduces handovers under some delays, but makes recovery after an actual failure take longer. This is a trade-off between recovery time and redundant computation. It does not replace the rule for accepting a write.

Not every lock is a lease. For example, MySQL GET_LOCK() belongs to a session and is released explicitly or when that session ends; committing a transaction does not release it. Choose a mechanism according to its actual semantics rather than assigning the properties of one lock type to every other type.

The generation reaches the resource

In our example, a fencing token is an integer that increases whenever permission for a particular job is newly acquired. A receives generation 1; B receives 2 after takeover. A worker supplies the job identity, owner, and generation with its write.

The important part is on the receiving side: the resource checks that generation before accepting a change. This active role of storage is explained in Martin Kleppmann’s discussion of fencing. A number in a worker log prohibits nothing unless it is checked at the write boundary.

Our model stores current ownership and the protected result in the same MySQL schema, in InnoDB tables. It can therefore require an exact match with the current generation immediately after takeover, even before B writes its result. That is a more specific condition than rejecting numbers below the last observed write: storage can see the current ownership claim itself.

A generation is not a secret. Supplying 99 grants no more permission than 2: the value must equal the current generation. Meanwhile, someone with direct database access can forge both the owner and the generation. Authentication and protection against untrusted clients are outside this local experiment.

One clock and three separate connections

The teaching job has key report-pine and immutable input pine. A worker prepares the text result PINE; A’s incorrect late result is labelled STALE. These synthetic values are easy to distinguish when inspecting the table.

The database contains three tables. jobs stores state, owner, generation, and lease_until; effects stores the accepted result with its owner and generation; fixture_clock holds shared logical time. The experiment controller may only move that clock forward. Worker methods do not accept a caller-supplied now parameter.

The boundary rule is unambiguous: permission is valid when now < lease_until. Equality means it has expired. At time 0, A acquires permission until 10; at 9, B cannot take over; at 10, it can. Renewal after that boundary is also rejected, even if there is no new owner yet.

This controlled clock tests event ordering; it does not simulate the accuracy of server time. A real system must separately define its authoritative time source, the effects of clock jumps, and the rules after storage failure. Two workers’ independent, uncoordinated clocks cannot silently be treated as one clock.

The controller, A, and B open three separate native PDO connections to one MySQL schema. Calls occur in a defined order; no sleep() must happen to hit the right moment. This tests controlled interleaving between real database sessions, not simultaneous execution by two OS processes or a network partition.

Permission checks and effects share one commit

Each mutation runs in an InnoDB transaction. At REPEATABLE READ isolation, row locks and current locked reads provide coordination, rather than a global prohibition on all other writes. Contention can produce a native MySQL error: 1205 for a lock wait timeout or 1213 for a deadlock. These errors propagate to the caller, and the model rolls back its own active transaction. InnoDB error-handling rules matter because not every error automatically rolls back the entire transaction.

A new acquisition reads the current record under a lock and increments its generation in the same transaction. Before every transactional operation, FencedStore::transaction() first locks the singleton fixture_clock row. This deliberately serializes the store’s transactional operations even across different jobs: they cannot mutate independent jobs concurrently through this path. This is coordination through a shared clock row, not an InnoDB engine-level database-wide write lock. The generation survives release, and counter exhaustion must stop acquisition rather than reset it.

Completion uses a conditional update:

UPDATE jobs SET state = 'done'
WHERE job_key = ? AND owner = ? AND generation = ?
  AND state = 'leased' AND lease_until > ?

The last value is read from the shared clock inside the same transaction. If no row changes, the worker has no valid claim and no effect is inserted. If one row changes, the result is inserted into effects, and both changes commit together.

The transition to done appears before the INSERT, but it is not yet a separately completed fact. If insertion fails, the model rolls back its entire owned transaction and propagates the error. Another reader should therefore never receive a completed job without its result. To test this pair of states, fixture setup uses a separate migrator to install a trigger with native SIGNAL SQLSTATE '45000'; runtime operations perform DML only.

Expiry is checked when the transaction accepts the operation. Changes to the shared logical clock coordinate through locks in the same schema, so it cannot advance within this critical section. This is not a promise to finish the MySQL commit before a particular physical second.

Here the transaction covers only the brief acceptance of an already prepared result. Long computation happens earlier. Holding the job and clock row locks for the entire job would make takeover wait or fail with a locking error, making the lab investigate a different boundary.

A late worker can neither write nor release

The main scenario has this expected order:

Tick Event Generation in jobs Effect count
0 A acquires a lease until 10 1 0
10 B takes over with a lease until 20 2 0
10 A submits STALE; the write is rejected 2 0
10 A attempts renewal and release; both are rejected 2 0
10 B writes PINE; the job becomes done 2 1

A must be rejected before B writes. Otherwise the example would quietly rely on an existing result instead of testing ownership handover.

renew() checks the same tuple—job, owner, generation—and that the lease is still valid. It neither increments the generation nor shortens an already granted expiry. release() moves a valid record to ready and clears its owner and expiry, while retaining the counter. The next acquisition receives a new generation, even if the same worker acquires it.

After takeover, A’s release attempt must not remove B’s permission. Without that condition, a tidy-looking finally block could release someone else’s lock. An old handle remains old regardless of whether the process’s textual identifier changes.

B’s repeated completion also cannot create a second effect: done no longer satisfies state = 'leased'. This is a narrow local property of our schema. A fully specified idempotent API still needs a defined response to repeats, an immutable-intent check, and a result-retention policy.

Where the protection ends

The effects table participates in the check because it is written in the same database and transaction. It cannot recall an email, payment, or message sent to an external service before that check. If the external resource does not support the corresponding fencing contract, adding generation only to a local ledger will not protect it.

A lease does not prove exactly-once either. It defines temporary permission, fencing rejects a stale write, and idempotency defines the behavior of a repeated logical action. A particular operation may need these properties together.

Every path that mutates the protected result must apply the same check. An administrative writer that bypasses it, or another endpoint without it, breaks the model’s assumptions. Deleting the generation record or restoring an old database copy also needs an explicit decision: old handles must not match newly granted permission after history is reset.

For ordinary mutual exclusion in Symfony, begin with a suitable Lock store. The teaching table makes the resource’s contract after handover visible. It is not a proposal to replace framework components with a custom general-purpose queue.

Reproducing the prepared sequence

The example evolves one existing Symfony application through classes, a command, and tests. It includes no copy of Kernel, composer.json, or vendor. It requires Symfony 8.1, PHP 8.4.1+, PDO MySQL, and MySQL 8.4. The guarded test fixture provides App\Infrastructure\MysqlLab: a separate migrator prepares InnoDB tables and FK/CHECK constraints before business transactions, while the runtime account has DML access only and cannot execute CREATE, ALTER, or DROP. MySQL DDL can cause an implicit commit, so this setup is not an atomic schema upgrade or an automatic transfer of data from the old SQLite database.

After integrating the files and registering the command, run the tests and demonstration through the shared guarded MySQL wrapper. It supplies the lab server configuration; the helper prepares a separate disposable schema before worker calls:

bash fixtures/mysql_labs/run.sh env APP_ENV=test APP_DEBUG=1 php vendor/bin/phpunit tests/LeaseFence --testdox
bash fixtures/mysql_labs/run.sh env APP_ENV=test APP_DEBUG=1 php bin/console app:lease-fence-demo --no-ansi

The store checks cover equality at expiry, takeover, stale completion/renew/release, repeated writes, rollback, lock contention, a new connection, and independent jobs. They use real, separate native MySQL connections sharing one schema. The kernel test also verifies command registration rather than only calling the class directly.

Actual local results

An important renewal invariant is that expiry never shortens: if the current lease ends at 18, a request proposing an earlier boundary must not change it to 9. This numeric condition remains part of the MySQL version’s contract; an explanation based on SQLite storage-class ordering does not apply to it.

The controlled scenario checks table state through a separate fresh MySQL connection: clock 10, generation 2, expiry 20, owner worker-b, job done, and exactly one PINE result. Stale complete/renew/release by A are rejected before B completes; no effect exists before that completion, and B’s repeat adds no record. This checks defined call ordering between separate sessions, not simultaneous execution by two OS workers.

These checks are scoped to native MySQL 8.4/InnoDB and controlled session interleaving. They do not prove Redis or external-service behavior, distributed-clock behavior, crash or power-loss recovery, or exactly-once execution. Old environment versions and SQLite run results are not measurements of the MySQL version.

When designing a worker, trace its permission to the final write boundary. Where is it granted, when does it expire, how does it change after handover, and who rejects a late result? If the resource itself answers that last question within an atomic mutation, an old process pause no longer grants permission to overwrite new work.

The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.

Check the current example against an owned disposable MySQL schema:

bash fixtures/mysql_labs/run.sh php vendor/bin/phpunit tests/LeaseFence
  1. Caching When the cache is empty for everyone: examining cache stampedes
  2. Databases Handler idempotency: repeat the task without duplicating its result
  3. Platform Engineering Old events arrive later: revisions and asynchronous change ordering

A project by the author · Weather Solution200

After reading, a look outside.

Temperature, rain and wind in your city. Check the forecast and plan the hours ahead.

Check the forecast
Next article