DEV Community

Anton Brilliantov
Anton Brilliantov

Posted on

Moving Old Animals Out Without Closing The Zoo

Moving Old Animals Out Without Closing The Zoo - the cover: at night Nora leads old residents to a far enclosure marked archive while the main gate stays open and visitors stroll in

Moving Old Animals Out Without Closing The Zoo

Old residents move to a far enclosure at night, one at a time or a whole enclosure at once, and the gate never closes. Built and tested; who throws them out for good is not the library's call.


👋 Hi, I'm Anton - a software engineer. These days I work on a platform: contracts, generated code, data paths and the tooling around them. Running notes live on my GitHub: github.com/brilliant-almazov.

This part is about built and tested code in the shared library: two archive movers. How many services already run them in production, and how much faster their tables got, is not measured here and not claimed.

This is part 12 of the series on what a shared platform does for every service, told as a zoo. Maybe you already do it better, maybe you'd do it another way - this is how it is going, and where it stops.


Eleven parts ago the zoo got its signs: every resident described itself, and nobody had to keep a wiki about it. Since then the shared library grew a lot - new packages, new guards, and a generator that prints most of a service from one manifest. The second part of this series walks through what grew, one habit at a time, starting with the quietest one: how old things leave.

In real life

The yard is full. Nora cannot get visitors through: "They can't get past!" Miso, lying across the path, is not bothered: "I've lived here since spring." Nobody wants to close the zoo for a day to sort it out, and nobody wants to push Miso out of the zoo either - old is not gone.

A four-panel comic: Nora says visitors can't get through and Miso says I have lived here since spring; Pip by a lamppost says the gate stays open and they move at night; Biscuit next to a cage says whole cage, one go, no recounting; Ember on her gold says old gold stays, she only moved it, and Nora asks who throws it out - not you

So the move happens at night, and the gate stays open. Pip moves residents one by one along a lit path to a far enclosure, and a resident who was already moved is not moved twice. When a whole enclosure is old, Biscuit does not carry the animals one at a time: the enclosure is unhooked, rolled to the far yard and hooked on again - and nobody recounts the animals at the new place, because the label on the door already says exactly who is inside. And Ember, guarding her gold, says the thing that matters most: the old gold stays, she only moved it. Who throws anything out for good is someone else's decision.

Heavy tables

A service that processes events, runs or readings for months ends up with a heavy working table where most rows are old. The new rows are the ones everyone reads and writes; the old ones still count in every index, every vacuum and every query plan. Teams usually reach for one of two things. A cleanup job that removes old rows in a loop - which works until the loop holds a lock at the wrong moment. Or a by-hand script that copies rows somewhere else and removes them - which works until it runs twice, or dies halfway.

The library's archive package is the night move. It holds two movers, both built and tested: one that moves rows, and one that moves a whole partition. The point of both is the same: keep the working tables light without closing the gate.

Three tiles with faces: the working table, worried; the archive mover, proud; the archive schema, happy; labels read old rows or old partition, and one step, idempotent; pills read built and tested

One statement for rows

The row mover exists for a processing need, not for cleanup. A service that processes events, runs or readings writes into a busy table all day, and the processing only ever needs the fresh part of it. The mover takes the old rows out of that table and puts them into the archive in one all-or-nothing step: either the whole batch is in the archive and gone from the working table, or nothing changed at all. A row already in the archive is not copied twice, so the move is safe to repeat - if it runs twice, the second run finds nothing new; if it dies halfway, nothing happened. The step runs with a lock timeout and a statement timeout.

The two timeouts are the part I like most. A move that cannot get its lock in time gives up instead of waiting behind a long query and making everyone wait behind it. A move that runs too long is cut. In both cases the next run picks up where this one did not start, because the statement is all or nothing and safe to repeat.

Three steps for a whole enclosure

For a table partitioned by time, moving rows one statement at a time is still too much work: the old partition is a whole enclosure, and it can move as one. The partition mover does three steps: detach the partition concurrently, move it to the archive schema, attach it to the archive table.

A night scene of the two movers, no code: rows - old residents walk a lit path into the archive enclosure under a sign all or nothing, safe to repeat, with two clocks for the lock timeout and the statement timeout; partition - a whole cage is detached, moved to the archive and attached in three steps, its door labelled CHECK = bound, no rescan; pills read built and tested

Step Zoo What it protects against
detach concurrently unhook the enclosure while visitors walk around a lock that stops the whole table
set schema roll it to the far yard copying every row one by one
attach hook it to the archive fence a long scan of every row at the new place
recover find an enclosure left on the road a move that stopped halfway

The attach is where the time usually goes. When Postgres attaches a partition, it must be sure that every row belongs inside the partition's bounds - and if nothing tells it so, it scans the whole partition. The mover makes sure something does: the partition carries a CHECK constraint equal to its bound, and the library checks that equality against the catalog before it attaches. With that constraint in place, Postgres trusts it and skips the scan. That is the label on Biscuit's door.

Columns: rows scanned on attach - when the CHECK is not equal to the bound, all rows; when it equals the bound, none; Nora, proud, says no recounting the animals; a pill reads a shape, not a measurement

The fourth row of the table is the honest one. A concurrent detach can be interrupted, and then the partition sits in a pending state - unhooked from the old fence, not yet at the new one. The mover's recovery reads the catalog of inheritance and the pending-detach flag to find such partitions and finish the move, instead of leaving an enclosure on the road.

An animation: a parcel travels under four tiles - the working table, detached, the archive schema, attached - and the pill changes from an old partition to detach concurrently, set schema, and attach: CHECK equals the bound, no rescan

Switches and numbers

A service turns a mover on through settings, not code. The keys follow one pattern per archive, and the mover reports three metrics - how many rows moved, how many partitions moved, and how many moves failed, by kind of failure:

ARCHIVE_<NAME>_*                         settings of one archive, by name
archive_moved_rows_total                 rows moved
archive_partitions_moved_total           whole partitions moved
archive_move_failures_total{kind}        failed moves, by kind
Enter fullscreen mode Exit fullscreen mode

Bars: statements to move rows 1; steps to move a partition 3; metrics it reports 3; timeouts it sets 2; Pickle, happy, says three steps for a whole cage; a pill reads counted from the library, not a load test

The failure metric with a kind is not a detail. Part of the same release wave made every method metric in the library say why a call failed, not only that it failed - and the archive does the same. A lock timeout at night and a broken constraint are very different mornings.

What went wrong

Nothing in this part comes with a war story, and I would rather say so than invent one. What I can show is the edge the design is built around: the partition that stops halfway. A concurrent detach is two steps inside Postgres, and a process that dies between them leaves the partition pending. A mover that did not know about that state would try again from the start and fail, or worse, report success while the old partition hangs between two tables. Reading the pending flag on recovery is the whole fix, and it is a fix for a failure that is easy to cause and quiet when it happens.

Before and after: everything in one table - heavy, old rows slow the new ones; risky, a cleanup that locks the yard - and old rows in the archive - light, the working table holds today; open, no lock beyond the timeouts; pills read built and tested

Partitions themselves are declared in the manifest, as a block of the Postgres pool. In the shape of the manifest - a form, key names illustrative:

# service.yaml - the platform creates these partitions; it never detaches or drops old ones
infra:
  postgres:
    main:
      partitions:
        events:
          name: events_YYYYMMDD    # the name is set whole
          ahead: 3                 # created ahead; 3 by default
          schedule: "0 3 * * *"    # the worker's run; the server also creates them on start
Enter fullscreen mode Exit fullscreen mode

A night mover with a lantern holds a manifest board with the partitions block - events, name events_YYYYMMDD, ahead 3, schedule 0 3 * * * - while another mover wheels sleepy old residents to the archive and Ember watches from her gold

The other edge is a decision, not a bug. The library creates partitions ahead of time and moves old ones on request, but it never detaches old partitions on its own schedule and never drops them. Throwing data out is a business decision with a retention rule behind it, and a shared library that drops partitions by default would make that decision for every service at once. Ember keeps the gold; someone with the right to decide throws it out.

Service tiles with faces: the working table happy, the row mover and the partition mover proud, the archive schema happy; visitors happy, metrics happy, a detach left halfway worried, dropping old ones bored; pills read built, tested, and dropping old partitions: not the platform's job

What I do not claim

  • Not that many services run the movers in production yet. The movers are built and tested in the library.
  • Not a measured speed-up of any table. The scan figure is a shape, not a measurement.
  • Not that the platform cleans up old data. It moves; it never drops.
  • Not the exact statement. The move above is described in words, not in code.
  • Not that a lock timeout is free. A move that gives up is retried later, and that later has to come.

What of this is method

  • Move in one step. All or nothing, a row already in the archive is not copied again, safe to run twice.
  • Let the constraint do the counting. A CHECK equal to the bound turns a scan into a trust.
  • Moving is not deleting. The library moves; the decision to drop stays with the service.

Zoo keeping, built in - Part 12. Next: Only One Keeper Opens The Gate.

If you archive old rows, do you move them in one statement or in a loop? If you partition by time, who decides when an old partition leaves? If you had a detach stop halfway, how did you find it? Which old resident in your zoo is still lying across the path?

Top comments (0)