skip to content

Session records kept in an ordinary relational table do not expire by themselves — what stops an expired one working, and what removes it?

level: middleimportance: should knowfreq 42%

answer

  1. two jobs, not one
  2. a deadline stored on the row
  3. the read path decides validity
  4. batched deletes on an indexed column
  5. what a key-value store does natively

basics

~20 s

The read path stops it: every lookup compares the row's stored expiry time with the current time and treats an expired row as absent. A scheduled purge job then deletes expired rows in batches so the table stays bounded.

solid answer

~50 s

Two separate mechanisms. **Validity** is decided on read: the row stores an `expires_at`, and every lookup treats a row past that time as missing, usually by putting the condition in the query itself, so a session ends on time even if no cleanup has run. **Removal** is a scheduled purge job that deletes rows past their expiry in bounded batches, using an index on `expires_at` so each run touches only expired rows and holds locks briefly. If the purge stalls, that read check still keeps every session within its deadline, but the table and its index keep growing, so the job needs its own monitoring. A shared key-value store folds both into **per-entry expiry**: the application writes the record with a lifetime and the store stops returning it afterwards, which is different from eviction, where a full store drops records before their deadline.

code

pseudocode · 11 lines
pseudocode
function loadSession(id):
    row = sessions.findById(id)
    if row is null or row.expiresAt <= now():
        return null            // expired counts as absent, purged or not
    return row

scheduled at a fixed interval:
    function purgeExpired():
        repeat:
            deleted = sessions.deleteWhere(expiresAt <= now(), limit = 1000)
        until deleted < 1000

go deeper

for a junior

Recall that a session row stores its own expiry time, and that something must both reject rows past it on every lookup and eventually delete them.

for a middle

Explain the two mechanisms, the read-time check that decides validity and the batched, indexed purge that removes rows, and contrast them with a key-value store's per-entry expiry.

for a senior

Show you would monitor the purge by the age of the oldest expired row, keep deletes batched to avoid long locks, and, given a read-time check, treat a stalled purge as a growth problem rather than a security hole.

for a principal

Weigh whether carrying a purge job and its monitoring is cheaper than a store with native expiry, given session volume and the cost of operating one more tier.

## Why a table needs two mechanisms A **session record** has a deadline: the moment after which the identifier that points at it must stop working. Where that deadline lives decides how much the application has to do. A shared key-value store usually accepts a lifetime with each write and enforces it itself. An ordinary **relational table** does not: a column called `expires_at` is just data, and the database will return the row a year later if asked. Some databases offer a row-expiry feature, but the common case is a plain table. So the application splits expiry into two jobs that are easy to conflate: - **Validity**: deciding, on each request, whether the session is still alive. - **Removal**: eventually deleting rows that are no longer alive, so storage stays bounded. Validity has to be exact and immediate. Removal only has to happen eventually. ## Rejecting expired rows on read The read path owns validity. Every lookup of a session by identifier compares the stored deadline with the current time and treats an expired row exactly as if it did not exist. - The simplest form puts the condition in the lookup itself, so an expired row is never handed to application code. - The comparison uses the server's clock, never a time the client sends, and the deadline that counts is the one stored with the record, not the cookie's own lifetime, which the client controls. - When a session's deadline moves forward on activity, the deadline column is rewritten on those requests; when to do that is a lifecycle decision, but it means the table sees writes as well as reads. With this check in place, a session ends on time even if no cleanup has run for days. ## Purging expired rows Removal belongs to a **scheduled purge job**. A well-behaved run looks like this: 1. Select rows whose `expires_at` is earlier than now through an **index on that column**, so the run touches only expired rows rather than scanning live ones. 2. Delete them in **bounded batches**, each in its own short transaction, so locks are held briefly and sign-in checks against the same table are not stalled. 3. Repeat until a batch comes back smaller than the batch size, then stop until the next scheduled run. 4. Record how many rows were deleted and the age of the oldest expired row still present. A few properties follow: - The interval is a tuning choice, not a correctness one: as long as the read check exists, a slow purge costs storage and query speed, not security. - Deleting on read is not a substitute. A session whose user never comes back may never be read again, so its row would stay indefinitely. - If several instances each run the job at once, their deletes compete for the same rows and waste work; running it from one place, or taking a lock first, avoids that. ## How the other homes handle expiry | Home | Who decides validity | Who removes expired records | What goes wrong | |---|---|---|---| | Process memory | The application, on read | An in-process sweeper | Every record vanishes on restart anyway | | Shared key-value store | The store, through per-entry expiry | The store itself | Records can also disappear early through eviction | | Relational table | The application's read path | A scheduled purge job | A stalled purge lets the table grow | The key-value store's convenience is real: one write with a lifetime replaces both the read check and the purge. Its cost is a separate tier to operate, and per-entry expiry is not eviction: expiry is loss the application asked for, eviction is loss a full store may force before the deadline. ## Common mistakes - Relying on the purge job for validity, so a missed run lets expired sessions keep working. - Trusting the cookie's expiry instead of the deadline stored on the server. - Running one unbatched delete over millions of rows at the busiest hour. - Monitoring only whether the job ran, not how far behind it is.

  • What happens to users if the purge job stops running for a week?
    No session outlives its deadline, provided the read path checks the stored expiry: expired rows are still rejected. The cost is operational: the table and its index keep growing, lookups over them can slow down, and the eventual catch-up deletes a week of rows, which must stay batched. Alert on the age of the oldest expired row, not only on job failure.
  • Why not simply delete each expired row at the moment a read finds it?
    Deleting on read only removes rows that someone asks for again; a session whose user never returns may never be read, so its row would stay indefinitely. It also turns a read into a write on the busiest path. Delete-on-read can complement a purge job, but it cannot replace one.

  • If the purge job runs often enough, the read path need not check expiry.
  • An ordinary relational table deletes rows on its own once their expiry column passes.
  • The cookie's own expiry is enough to end a server-side session on time.
  • Deleting an expired row when a read finds it keeps the table bounded without a scheduled purge.
  • The purge should delete every expired row in one statement to keep it simple.