DEV Community

kevindev
kevindev

Posted on

PostgreSQL Leases for Email Test Fixtures

Email verification tests often fail for a reason that is not really email: two test runs are using the same inbox. One run deletes a message that the other run still needs, or a retry reads a verification code that belongs to an earlier attempt.

I prefer treating a test inbox as leased data. A test claims one fixture for a limited period, refreshes that lease while it is active, and releases it when the test finishes. PostgreSQL is a good place for this small coordination problem because the claim and the state transition can happen in one transaction.

The same idea works when a test uses a temp mail.so address or a facebook temp email flow. The provider is not the important part. Ownership and expiry are.

Why email fixtures need a lease

A simple email_fixtures table with an available boolean looks fine at first. It becomes weak when CI runs in parallel:

  • Two workers read available = true before either worker updates it.
  • A killed job leaves a fixture marked busy forever.
  • A slow verification message arrives after the test has already moved on.
  • A retry has no clear record of which run owns the inbox.

The lease model gives each claim an owner, an expiration time, and a status. The lease is not a promise that a test will finish; it is a small contract that say who may read the fixture right now.

The PostgreSQL lease model

Here is a minimal schema. Keep provider credentials out of this table if possible; the fixture record only needs a stable identifier and the data required for cleanup.

CREATE TABLE email_fixtures (
    id              bigserial PRIMARY KEY,
    address         text NOT NULL UNIQUE,
    provider_key    text NOT NULL,
    status          text NOT NULL DEFAULT 'available',
    lease_owner     text,
    lease_expires_at timestamptz,
    created_at      timestamptz NOT NULL DEFAULT now(),
    updated_at      timestamptz NOT NULL DEFAULT now(),
    CHECK (status IN ('available', 'leased', 'retiring'))
);

CREATE INDEX email_fixtures_claim_idx
    ON email_fixtures (status, lease_expires_at);
Enter fullscreen mode Exit fullscreen mode

An expired lease should be treated as available during a claim. That avoids a separate cleanup job becoming a hard dependency for every test. A cleanup worker is still useful for deleting old messages and retiring broken addresses, but claiming should be self-healing.

Claiming a fixture safely

The important details are FOR UPDATE SKIP LOCKED and the ownership token. SKIP LOCKED lets parallel workers move to another row instead of waiting behind a fixture already being claimed.

WITH candidate AS (
    SELECT id
    FROM email_fixtures
    WHERE status = 'available'
       OR (status = 'leased' AND lease_expires_at < now())
    ORDER BY updated_at, id
    FOR UPDATE SKIP LOCKED
    LIMIT 1
)
UPDATE email_fixtures AS f
SET status = 'leased',
    lease_owner = $1,
    lease_expires_at = now() + make_interval(secs => $2),
    updated_at = now()
FROM candidate
WHERE f.id = candidate.id
RETURNING f.id, f.address, f.provider_key, f.lease_expires_at;
Enter fullscreen mode Exit fullscreen mode

Run this statement in a transaction. If it returns no row, the pool is exhausted, so the test should report a useful capacity error instead of silently sharing an inbox. The owner can be a test-run ID plus a worker ID, such as run-1842/worker-3.

The API that starts a test can return the fixture ID and an opaque lease token. Do not let callers update a fixture using only its address. An address is an identifier, not proof of ownership.

Reclaiming abandoned leases

CI processes get cancelled. Termination hooks are helpful but not reliable, so expiry must be the authority. A heartbeat extends the lease only when the owner still matches:

UPDATE email_fixtures
SET lease_expires_at = now() + interval '2 minutes',
    updated_at = now()
WHERE id = $1
  AND status = 'leased'
  AND lease_owner = $2
  AND lease_expires_at > now();
Enter fullscreen mode Exit fullscreen mode

If the affected-row count is zero, the worker no longer owns the fixture. It should stop polling immediately and mark the test as interrupted. This check also catch a common race: an old worker wakes up after another run has already reclaimed the row.

Release is similarly conditional:

UPDATE email_fixtures
SET status = 'available',
    lease_owner = NULL,
    lease_expires_at = NULL,
    updated_at = now()
WHERE id = $1 AND lease_owner = $2;
Enter fullscreen mode Exit fullscreen mode

Connecting the lease to a REST API test

A small service boundary keeps test code uncomplicated:

  1. POST /test-fixtures/email/claim claims a row and returns its token.
  2. The test creates a user through the REST API using the returned address.
  3. A poller reads only messages associated with that fixture and run.
  4. The test calls a heartbeat while it waits for verification.
  5. POST /test-fixtures/email/release releases the row in a finally path.

The poller still needs a deadline and a message identity check. A matching subject is not enough if an old message remains in the inbox. Store the message ID or received-at watermark after the claim, and accept only a message that arrived for the current run. For wait behavior, these poll-based email waits are a useful companion pattern.

If the service supports user email changes, keep the fixture policy separate from application trust policy. These trust tiers for email changes help explain why a test address should not automatically receive production-level privileges.

One practical naming note: search logs sometimes contain misspellings such as tempail or temp mailid. Keep those terms as searchable plain text if your diagnostics need to recognize them, but never use a typo as an authorization key.

Operational checks that matter

Add metrics before the first flaky failure arrives:

  • claim success and pool-exhaustion counts;
  • lease age at release;
  • expired leases reclaimed;
  • heartbeat failures;
  • verification poll duration;
  • messages rejected because their run ID did not match.

Alert on a growing number of expired leases and on a pool with no available rows. The cleanup worker can be boring, and that is good. It should remove old messages, retire unhealthy provider addresses, and leave a reason in an audit log.

For PostgreSQL, keep transactions short. Claim the row, commit, and perform provider calls outside the transaction. Holding a database lock while waiting for an email makes contention much harder to diagnose.

Final checklist

Before relying on leased fixtures in CI, verify that:

  • every claim has a unique owner and expiry;
  • concurrent claims use row locking with SKIP LOCKED;
  • heartbeat and release require the owner token;
  • an expired lease can be reclaimed without manual repair;
  • polling has a deadline and checks message identity;
  • cleanup is safe to retry;
  • logs avoid printing inbox contents, tokens, or provider secrets.

This pattern keeps email verification tests deterministic without pretending that the external mailbox is perfectly reliable. PostgreSQL coordinates ownership, the REST API exposes a narrow lifecycle, and the test remains responsible for deadlines. That separation makes failures easier to reproduce and much less mysterious.

Top comments (0)