All writing

Putting a time limit on batch writes in a PL/SQL API

This post is about giving a write request a time limit in an API that lives mostly in Oracle PL/SQL, where one request can create, update, upsert or delete a whole list of objects, and the layer in front of it wanted to be able to say “you have this many seconds, then stop”. For a read that’s simple, you cancel the query and nothing changed, but for a write it isn’t, because by the time the limit passes some objects are saved, one may be halfway through, and the rest never started, and the caller has to be able to tell which is which.

Most of the work went into two questions, where the deadline gets checked, and what happens to work that can’t be cut in the middle when it passes.

One deadline, computed once

Every write already went through one entry procedure, so the limit comes in there as an optional number of seconds and gets turned into one absolute point in time right at the start, which is then passed down to every loop that does the writing:

if p_limit_s is not null then
   l_stop_at := systimestamp + numtodsinterval(p_limit_s, 'SECOND');
end if;

It has to be computed once like this, because if every inner call got “N seconds” and measured them from its own start, each one would get the full budget again, and the request as a whole would have no limit at all.

The check is a tiny function, and a null deadline means “no limit”, which keeps every existing caller on exactly the behaviour it had before:

function time_is_up(p_stop_at in timestamp with time zone) return boolean is
begin
   return p_stop_at is not null and systimestamp >= p_stop_at;
end;

Checking where an object starts

Where to call it matters more than the check itself, since the write loops don’t go over objects, they go over field entries (one row per field of each object, with all rows of one object next to each other), so checking on every iteration would happily stop between the third and the fourth field of a record. The check has to sit exactly where a new top-level object starts:

for i in p_rows.first .. p_rows.last loop
   if time_is_up(p_stop_at)
      and (i = p_rows.first or p_rows(i).obj_id <> p_rows(i - 1).obj_id)
   then
      mark_rest_as_skipped(p_rows, i, p_answers);
      exit;
   end if;
   -- handle field i as before
end loop;

At that point the previous object is finished (for creates and updates that also means committed, while deletes commit once after the loop, which is fine because nothing past the stop gets touched), and nothing of the next object has been touched yet, so stopping there leaves the data in a state the caller can reason about. Every object that never started still gets an entry in the response, in its own position, with a “not processed” code instead of the whole request failing, so the caller can see exactly which ones to send again (for deletes the entry also carries the id, since that’s all a delete has).

Child objects never check the deadline. Some creates are hierarchical, a parent with its children in the same request, and the children are saved by calling the same create logic again. If a child could stop, the parent that had already started would fail and get rolled back by default, or, with the request’s “stop on error” option turned off, it would be saved with only some of its children, and neither is what a time limit should do. The deadline parameter defaults to null and the variant the hierarchy calls doesn’t take one at all, so a child can’t check by accident (the test for that has nothing to delete to make it fail, so it was checked against a copy of the code where the child call does get the deadline, which turns it red).

Every other path that writes has to get the deadline though, and the one that’s easy to miss is the upsert, where objects that already exist go through the update logic. Nothing exercised that call at first, so removing the deadline from it left every test green, which is why it’s worth reading the requirement next to the code and not only trusting that the tests that exist go red.

The path where stopping between objects wasn’t enough

One write path saves groups of related records, and it works in two phases, the first walks every record in the request and prepares it, and the second saves whole groups. The records of one group can be anywhere in the request, so a group of three might be records 2, 40 and 97.

My first version checked the deadline per record in the first phase, the same way as everywhere else, and it turned out that a stop between record 2 and record 40 would let the second phase save that group with one record out of three, even though all three were fine. An error on a record that’s already been matched to its group makes the second phase skip the whole group, so a stop shouldn’t be the thing that saves part of one.

So instead of moving the check again, the whole first phase became something we can undo:

if p_stop_at is not null then
   savepoint before_prepare;
end if;

while l_rec is not null loop
   if time_is_up(p_stop_at) then
      rollback to before_prepare;
      l_groups.delete;
      -- every record without an error of its own answers "not processed"
      ...
      exit;
   end if;
   -- prepare record l_rec as before
end loop;

On a stop, everything the first phase wrote is rolled back, the in-memory list of groups the second phase would save is emptied (a rollback doesn’t touch PL/SQL variables, so that part is on us), and every record that doesn’t already have an error of its own answers “not processed”. It’s coarser than the other paths, since a stop throws away work that was fine, but a request like that is the kind of thing you resend as a whole anyway, and “nothing happened, send it again” is a much easier answer to act on than “some records of some groups happened”. I checked it with a scratch copy of the code that slept after the first record of a two-record group, with a 3 second limit, and both records came back “not processed” with nothing changed, while the earlier version saved the first record alone.

A savepoint only helps if nothing between it and the rollback commits or rolls back. A commit (or a full rollback, or DDL with its implicit commit, even somewhere deep in a called procedure) erases the savepoint, and rollback to then fails with ORA-01086 instead of undoing anything. The first phase here doesn’t commit, which is the only reason this works, so it’s worth checking every procedure the protected code calls before reaching for the same trick.

Making the stop itself cheap

The first version also built each “not processed” answer separately, one per remaining object, and building an answer isn’t free (it looks up the error text, among other things). For a big request that stops early, all of that is time spent past its own deadline only on telling the caller that it stopped, which is a bit silly for a feature whose whole point is to stop on time. Every one of those answers is identical (same code, same text), so the answer is now built once per stop and copied into each remaining position.

The mode that processes objects strictly in order, one call per object, didn’t check the deadline in its own loop at all and relied on the check inside each single-object call, so every object after the deadline still ran that call’s setup, built its own answer and wrote its own log row before finding out it shouldn’t run. Now its loop checks once per object, answers all the remaining ones with one answer, and logs the stop once.

Summary

A time limit on a write that touches many objects is only safe if you check it at a point where nothing is half done, which for most loops means where a top-level object starts and for child objects means never, and when some piece of work spans more than one iteration, a savepoint around it (with nothing inside that commits) lets you undo it on a stop instead of hoping the check lands between its parts. Computing the deadline once, giving every object that didn’t run its own “not processed” entry, and keeping the stop itself cheap are what make the rest of it usable for the caller.

Email address copied [email protected]