PubliraGitHub

Scheduled and maintenance jobs

Published Updated

Everything an install does without a request is done by publira worker: it publishes the episodes scheduled for now, tells the web apps which cached pages a change made stale, sends mail and push notifications, rebuilds the statistics and rankings, and deletes what has passed its retention period. Nothing else has to run on a timer, and no host cron or Kubernetes CronJob is needed. This page says what runs when, how to tell which job is behind a symptom, and how to run one by hand with publiractl job.

The interval of each job, the variables that tune it, and the full list of jobs are in the publira worker reference and the publiractl job reference; this page does not repeat them.

Which job is behind a symptom

Start from what you see, and look at the job that owns it:

What you seeJobWhere to look
An episode is still Scheduled after its timeScheduled publicationScheduled publication
An episode's site page still shows it priced inside its free reading period, or free after it endedFree reading periodsFree reading periods
The storefront's weekly schedule still shows yesterday as todayThe tenant day rolloverFree reading periods
A site banner is still up after its Stop showing at timePinned announcementsFree reading periods
A series is still missing from the site's lists after its Publication date and timeScheduled seriesFree reading periods
A campaign banner is still missing from the site after its window opened, or still up after it closedCampaign bannersFree reading periods
An episode's site page still quotes its regular price after a campaign price started, or the campaign price after it endedCampaign pricesFree reading periods
A reader's coin history does not show the coins that expired unspentCoin expiryOther scheduled jobs
An episode is still priced after the day its series' free-after-publication rule makes it freeFree after publicationOther scheduled jobs
A scheduled announcement has not gone out after its timeScheduled announcementsOther scheduled jobs
A page keeps showing what it showed before a changeCache revalidation, in the outboxThe outbox
A mail or a push notification never arrivesThe outboxThe outbox
The rankings, series ratings, or recommendations stop movingThe statistics and ranking chainStatistics and rankings
A month is not closed on a tenant's close dayThe royalty closeOther scheduled jobs
An episode bought on Google Play stays open after a refundThe Google Play refund syncOther scheduled jobs
The search does not move to a newly saved engineThe search index buildSearch
A payment reconciliation a Tenant admin started never finishesThe payment reconciliationsOther scheduled jobs
A reader's download of their data stays pendingThe data downloadsOther scheduled jobs
A tenant deleted from the Platform Console or with publiractl tenant delete is still listed as Deleting or deletingThe tenant erasureOther scheduled jobs
Old records are not deletedThe purgesOther scheduled jobs

Every one of them first needs publira worker to be running and ready: an install whose worker is stopped serves every page, but publishes nothing, sends nothing, and rebuilds nothing. GET /readyz on the worker names a check for each database login it signs in as, so a login that stopped answering is named there. On an install that splits the worker by queue, each job also needs a running worker that takes its queue, as Workers that take some of the jobs describes.

Where a job's failures are recorded

The worker logs every failure, and the log line names the job. Every run of a scheduled job also leaves a row in the river_job table of the database, where the worker queues its own work, so that table shows whether a job ran at all, and when.

What the row says about a failure depends on the job. The publication, free reading period, day rollover, pinned announcement, scheduled series, campaign banner, campaign price, coin expiry, free after publication, and scheduled announcement jobs finish their run even when something in it failed: each logs what it could not finish and leaves it for its next run, a minute later, so their rows read as completed and the failure is in the log alone. Every other job records a failed run in its row, keeping every attempt's error in the errors column, naming the tenant and the day it stopped on. Query it with psql, connected as the database's administrative login:

SELECT kind, state, attempt, finalized_at, errors
FROM river_job
WHERE state IN ('retryable', 'discarded')
ORDER BY id DESC
LIMIT 20;

retryable is a pass waiting for another attempt, and discarded one that ran out of attempts. A finished or cancelled row is deleted after a day, and a discarded one after a week, so look there soon after the symptom. The outbox keeps its own record, described below.

Scheduled publication

An episode staff scheduled is published by the worker once its time has passed, together with the notifications to the series' followers and the drop of the cached pages that listed it as scheduled. The worker looks for due episodes every minute, so an episode goes live within about a minute of its time.

A publication that fails is tried again a few times within the same pass. When every attempt fails, the episode stays Scheduled, and the worker writes a notification titled "An episode could not be published" for the tenant's administrators, in the tenant console, and for every operator, under Notifications in the Platform Console. Each such notification is written once per episode. The worker tries the episode again on every later pass, so once the cause is fixed — a database that was failing, a migration that had not run — the episode goes out on its own. Staff do not have to wait for that: entering the current time under Publishing settings on the episode's page in the tenant console publishes the episode in that request, without the worker. Its followers are still told by the worker, through the outbox.

Notifications in the Platform Console: an unread notification titled An episode could not be published, naming the episode, its series, and its tenant, with Mark as read and Mark all as read.

Free reading periods and other cached pages

Six jobs keep the web apps' cached pages on the right side of a time that passed:

  • Free reading periods. An episode inside a Free reading periods entry reads as free from the moment the period starts and is priced again once it ends, with no job involved: every read compares the period against the current time. What the job fixes is the pages a site cached before the boundary, which it marks stale at both ends of every period.
  • The tenant day rollover. At each tenant's own midnight, in the tenant's time zone, it marks stale the storefront's weekly schedule, the one page whose answer is the tenant's calendar day.
  • Pinned announcements. Once an announcement's Stop showing at time passes, it takes the announcement off the banner and marks the banner stale.
  • Scheduled series. A series saved with a Publication date and time in the future is public from that time, with no job involved: every read compares the time against the current one. What the job fixes is the series lists, the Author pages, and the series' own page that a site cached while the series was still hidden, which it marks stale once the time has passed. At the same pass it dates the episodes published while the series was hidden from that time, and hands their announcements to the outbox.
  • Campaign banners. A published campaign banner shows from the start of its window until its end, with no job involved: every read compares the window against the current time. What the job fixes is the banners a site cached before a boundary, which it marks stale at both ends of every published banner's window.
  • Campaign prices. An episode under a campaign price is quoted and charged that price from the start of the campaign until its end, with no job involved: every read and every checkout compares the campaign against the current time. What the job fixes is the episode pages and series pages a site cached before a boundary, which it marks stale at both ends of every campaign.

Each runs every minute. None of them drops a cache itself: each records the drop as an entry in the outbox, which the worker then sends to the web apps, so a page that stays stale while the worker has PUBLIRA_REVALIDATE_TOKEN is an outbox problem, described below.

A worker started without PUBLIRA_REVALIDATE_TOKEN has cache revalidation turned off. These jobs then record no drop at all, yet still count each boundary and each series' time as passed and take each banner down, so the outbox has nothing to retry, and restarting the worker with the token does not bring those drops back. The pages they would have dropped keep what they cached until the next change to the same thing drops them, or their cache runs out. Set the token on publira server and publira worker before the first boundary you need on time, as Installing describes.

These jobs have no publiractl job command, and need none: each acts on every time that has passed whenever it runs, including the first run after the worker starts.

Statistics and rankings

The statistics, rankings, series ratings, and recommendations are built from the reading activity once each day is over, in the tenant's own time zone. Four jobs do it, one after the other, as one chain:

  1. Reading projection (project-episode-reads) files every finished read as an analytics event.
  2. Daily statistics (aggregate-content-stats) rebuilds each finished day's views, completed reads, purchases, ratings, favourites, and comments per series and episode, and how far into each episode its readers got. The series ratings the storefront shows are computed from them. It also records which signed-in readers viewed, finished, or bought an episode that day, and in which series, which is what the console follows the readers who signed up in a week by. The upgrade to the release that introduced those records files them for every day whose analytics events were still kept; a day already purged by then has none, and cannot be given any afterwards.
  3. Rankings (aggregate-rankings) rebuilds the daily and weekly leaderboards the storefront's Ranking pages show.
  4. Recommendations (build-recommend-features) rebuilds the snapshot each reader's recommendations are drawn from.

The chain starts every hour, and each link starts the next when it ends. Since every tenant's midnight falls on a different hour, a tenant's day is rebuilt within about an hour after it ends, plus the time the chain takes. So a ranking that has not moved yet a few hours after a tenant's midnight is normal; one that has not moved for a day is not.

The worker remembers, per tenant, the last day each link finished, and starts from the day after it. A day that fails stops that tenant there while the other tenants carry on: the error is in the river_job row of the failing link, the pass is attempted up to three times, and the next hourly pass starts again from the day that failed. Once the cause is fixed, the tenant catches up on its own, every missed day in order.

Other scheduled jobs

JobHow oftenWhat it does
Free after publicationEvery minuteAdds a free reading period to each published, priced episode a series' free-after-publication rule has reached: the set number of days have passed since the episode was published, and it is not among the newest episodes the rule keeps priced. The period starts on that day, or where a period scheduled by hand that is still open then ends, and moves back to that day if that period is deleted. It lasts until the rule no longer covers the episode: saving the rule turned off, or with numbers that leave the episode out, removes it at once, and the next pass removes it from an episode that left the rule otherwise, such as one moved among the newest or taken down. The episode's pages are marked stale in the same pass, as a period that starts or ends does. Like the jobs that keep cached pages on time, it has no publiractl job command
Scheduled announcementsEvery minuteDelivers each announcement staff scheduled, as Announcements describes, once its time has passed: marks it delivered, which is what shows it to readers, hands its notifications to the outbox, and marks stale the readers' announcement pages and, for one shown as a banner, the banner. Like the jobs that keep cached pages on time, it has no publiractl job command
Coin expiryEvery minuteWrites an entry into a reader's coin history for each grant of coins that expired with coins unspent, so the history says where they went. The coins stop counting toward the balance at the moment they expire, with no job involved, and are never restored. Like the jobs that keep cached pages on time, it has no publiractl job command
Royalty close (close-royalty-statements)Every hourCloses each month a tenant on Close automatically owes, once the tenant's close day has come. A month already closed, by hand or by an earlier pass, is left as it is
Google Play refund sync (sync-google-play-voided-purchases)Every hourReads the purchases Google Play refunded in the last 30 days, for every tenant whose Google Play store is on, and takes them back, as Selling episodes describes
Search index build (build-search-index)Every 30 secondsBuilds the index on a newly saved search engine and moves the search onto it, as Search describes
Payment reconciliations (reconcile-payments)Every 10 secondsRuns each reconciliation a Tenant admin started, reading the payments of its period from the tenant's payment provider or store, as Selling episodes describes. A run the source refuses is recorded as failed for the Tenant admin to start again, rather than retried. A run a stopped worker was in the middle of is taken up again after two hours
Data downloads (build-data-exports)Every 10 secondsPrepares each copy of their data a reader asked for, stores it in the bucket, and tells the reader it is ready, as Reader accounts describes. A request made while no object storage is set up is recorded as failed for the reader to ask again, rather than retried. One a stopped worker was in the middle of is taken up again after 15 minutes
Tenant erasure (erase-tenants)Every minuteErases each tenant an operator deleted, from the Platform Console or with publiractl tenant delete, as Deleting a tenant describes: its rows in every table, its objects in the bucket, its documents in the search engine's index, and the converted images and rate limit counters it left in Valkey, and then the tenant itself, after which its hosts belong to no tenant. The deletion is recorded in the Platform Console's Audit logs, and every operator gets a notification titled "A tenant was deleted" under Notifications. A run that stops on an error leaves the tenant deleting, refused like a suspended one, and every operator gets a notification titled "A tenant could not be deleted", once per tenant; the next run, a minute later, takes the tenant up again from what is left, and the error is in the worker's log. A worker that is not given PUBLIRA_REDIS_URL leaves the converted images and the counters in Valkey to expire on their own: the images once their cache lifetime is up, and a counter once its window ends
The purges (purge-*)Every hour or every 24 hoursDelete withdrawn comments, analytics events, and ranking snapshots past their retention period, as Platform defaults and policies describes; the challenges a two-step sign-in has finished with, and the record of each sign-out once the session it ended would have expired; the readers' data downloads seven days after they were ready, and those of deleted accounts; the images nothing on any tenant uses any more, once they are a day old; and the webhook deliveries 30 days after they were delivered or given up

Workers that take some of the jobs

A worker started with --queue runs the jobs of the queues it names and leaves the others to the workers that name them, as Splitting the worker by queue describes. The jobs on this page are on seven queues, which river_job names the same way except outbox, which it names default:

QueueJobs
outboxThe outbox: mail, push notifications, cache revalidation, and the search engine's index updates
tickerScheduled publication, free reading periods, the tenant day rollover, pinned announcements, scheduled series, campaign banners, campaign prices, coin expiry, free after publication, and scheduled announcements
maintenanceThe statistics and ranking chain, the royalty close, the Google Play refund sync, and the purges
search_indexThe search index build
payment_reconciliationThe payment reconciliations
data_exportThe data downloads
tenant_erasureThe tenant erasure

Every queue needs at least one running worker that takes it. Whichever worker schedules the jobs schedules all of them, whatever queues it takes itself, so a job whose queue no running worker takes is not lost, but nothing runs it: it waits in river_job until a worker that takes its queue starts, and then runs as it would after downtime. Each worker logs the queues it leaves to others when it starts, as worker leaves queues to other replicas with not_hosted naming them. A queue whose jobs are waiting shows in river_job:

SELECT queue, kind, count(*), min(scheduled_at)
FROM river_job
WHERE state = 'available' AND scheduled_at < now() - interval '5 minutes'
GROUP BY queue, kind;

A row here is a job that has been due for five minutes and that no worker has picked up: start a worker that takes its queue, or add the queue to the --queue of a running one.

After downtime

A worker that was stopped, or that ran without a working database, does nothing for that time, and the work waits in the database rather than being lost. When it starts again:

JobOn start
The outboxSends every entry that was waiting. An entry a stopped worker was in the middle of is picked up again after 15 minutes
Scheduled publicationPublishes every episode whose time passed, and notifies its followers
Free reading periods, the tenant day rollover, pinned announcements, scheduled seriesMark stale every page whose boundary passed in the meantime, and take down every banner whose time ran out
Free after publicationOpens every episode whose day passed in the meantime, from that day
Scheduled announcementsDelivers every announcement whose time passed, and notifies its readers
The statistics and ranking chainRebuilds every day each tenant missed, in order, except the days whose analytics events have already passed their retention period, or were purged under a shorter period saved before: those are logged as missing and skipped, and cannot be rebuilt
Royalty closeCloses every month that became owed
Search index buildBuilds a pending index
Payment reconciliationsRuns every reconciliation started in the meantime
Data downloadsPrepares every copy asked for in the meantime
Tenant erasureErases every tenant deleted in the meantime, and finishes one a stopped worker was in the middle of
The purgesRun only when none has finished in its current hour or day, counted on the clock rather than from when the worker started; the first run then deletes everything that expired in the meantime
Google Play refund syncRuns, like a purge, only when none has finished in its current hour. A worker that was down longer than 30 days misses the refunds Google Play no longer lists

The waiting interval is what keeps a restart or a deploy from being a sweep of every table and of the whole bucket.

The outbox: mail, push, and cache revalidation

Every side effect a request leaves for later — a mail, a push notification, the drop of a cached page, an index update for the search engine — is written to the outbox in the same transaction as the change that caused it. So a change is never saved without its side effect, and the worker sends the entry within a few seconds.

An entry that fails is tried again, waiting twice as long after each failure: one second, then two, then four, up to an hour between attempts. After the sixteenth failed attempt, about four hours after the first, the entry is given up: it becomes dead, and the worker does not send it again on its own. An entry that can never succeed, such as a mail to an account that was deleted, is given up at once. An entry of a kind the worker does not know has not failed: during an upgrade it is one only the new release writes, so the worker leaves it for a worker of the new release, looking at it again every minute, and gives it up only a day after it was written. What failing means depends on the entry:

  • Mail fails while the SMTP server, or email-renderer once it is on, refuses or cannot be reached, as Email describes.
  • A push notification to a phone is skipped rather than failed while the tenant has no Firebase credentials saved, so it is not retried once they are. Browser notifications are sent only once Web Push is turned on, as Web Push describes.
  • A cache revalidation fails while a web app is down. A worker without PUBLIRA_REVALIDATE_TOKEN fails every drop publira server or publiractl recorded, on every attempt; the drops of its own jobs it does not record at all, as Free reading periods describes.
  • A webhook delivery, of event_type webhook_delivery, sends one event to an endpoint a Tenant admin saved, as API keys and webhooks describes. It fails while that endpoint is down or answers anything but 2xx, and is given up at once when it answers another 4xx but 408 and 429, or its host resolves to a private, loopback, link-local, or shared address. The endpoint is a server the tenant runs, so a failing delivery is the tenant's to fix rather than the install's. A delivery whose endpoint's signing secret no key in PUBLIRA_SECRET_ENCRYPTION_KEYS opens waits, without spending an attempt, until the key is back or the secret is rotated.
  • A Google Play purchase or subscription made in the app is acknowledged through the Google Play Developer API, and Google Play refunds one nobody acknowledged within three days. The acknowledgement fails while that API is down, and keeps being tried for those three days. While the tenant's Google Play store is switched off, or its key cannot be decrypted, it waits without spending an attempt, until the three days are out.

PUBLIRA_OUTBOX_MAX_ATTEMPTS on publira worker sets the number of attempts. The wait keeps doubling up to an hour between attempts, so each attempt past the sixteenth lets an entry outlast an hour more of an outage. A webhook delivery has a budget of its own of 20 attempts, about eight hours, and a Google Play acknowledgement one that lasts the three days, whatever PUBLIRA_OUTBOX_MAX_ATTEMPTS says: the server a webhook goes to may be down for longer than an install's own services, and a Google Play purchase has a deadline.

The worker sends webhook deliveries over HTTPS to whatever host and port each endpoint names, so an install that restricts the worker's outbound traffic has to allow them for webhooks to arrive.

Seeing what was given up

The worker logs each entry it gives up on as outbox event dead, and counts it in the publira.outbox.events.dead metric once its metrics are turned on, as Monitoring describes; alert on either. The entries themselves stay in the outbox_events table, with the last error:

SELECT event_type, tenant_id, attempts, last_error, updated_at
FROM outbox_events
WHERE status = 'dead'
ORDER BY updated_at DESC
LIMIT 20;

publiractl outbox list prints the same entries with the tenant each belongs to. Once whatever failed them is fixed, publiractl outbox requeue puts dead entries back in the queue with their attempts back to zero, and the worker sends them within a few seconds. Name them by ID with --event, by kind with --type, or by tenant with --tenant, or give --all to requeue every dead entry:

publiractl outbox list
publiractl outbox requeue --type contact_message_reply_email

Run it with the image of the release the install runs, with PUBLIRA_PLATFORM_DB_URL set to the publira_platform connection. A requeued entry is sent as late as the outage made it: a mail about a comment arrives hours after the comment was written. The flags and what each command prints are in the publiractl outbox reference.

What a dead entry costs until it is requeued depends on its event_type:

  • A mail does not arrive. A password reset, a confirmation mail, and an administrator invitation cannot be requeued, because the entry no longer holds the mail's link: a reader asks for a new password reset or confirmation mail, and an administrator invitation is resent, as A tenant's staff describes.
  • A push notification does not arrive, and the notification stays in the reader's list on the site and in the app.
  • A cache revalidation leaves the pages it named showing what they showed before, until the next change to the same thing drops them again or their cache runs out.
  • A Google Play acknowledgement leaves the purchase to be refunded by Google Play at the end of its three days.
  • A webhook delivery is not requeued here. It is listed as Dead on the tenant console's API keys and webhooks, where a Tenant admin resends it once the endpoint is fixed.

Running a job by hand

publiractl job <job> runs one pass of a maintenance job and exits. It runs the same code as the worker's scheduled pass, not a copy of it, so it behaves the way the scheduled pass does. It is for what the schedule does not do:

  • A backfill: rebuilding the statistics of a named day the chain has already passed.
  • A dry run: counting what a purge would delete before it deletes it.
  • Applying a change now: a shorter retention period you just saved, purged now rather than at the next daily run.
  • Debugging a pass that fails, with its log in front of you.

Run it with the image of the release the install runs, with PUBLIRA_CONTENT_STATS_DB_URL set to the publira_content_stats connection:

docker run --rm -e PUBLIRA_CONTENT_STATS_DB_URL \
  publira/publiractl:<tag> job purge-content-events

On a Docker Compose install, docker compose run --rm publiractl job purge-content-events has the connection already. The image purge, the data downloads and their purge, the Google Play refund sync, the payment reconciliations, the search index build, and the tenant erasure also need PUBLIRA_SECRET_ENCRYPTION_KEYS and PUBLIRA_SECRET_ENCRYPTION_PRIMARY_KEY_ID when the credential they use is saved in the install, as the bucket's access key, a tenant's payment provider and store credentials, or the search engine's password is. The tenant erasure also takes PUBLIRA_REDIS_URL, the one publira server is given, to reach the converted images and the counters in Valkey.

A job logs to standard output, and exits 1 when the pass failed. A job that works through the tenants one at a time finishes the others before it exits, and its log names each tenant that failed.

Dry runs

Every purge takes a variable that makes it count instead of delete, such as PUBLIRA_CONTENT_EVENTS_PURGE_DRY_RUN=true for purge-content-events; the name for each purge is in its reference. The count is in the log:

docker run --rm -e PUBLIRA_CONTENT_STATS_DB_URL \
  -e PUBLIRA_CONTENT_EVENTS_PURGE_DRY_RUN=true \
  publira/publiractl:<tag> job purge-content-events

A purge reads the retention periods when it starts, so a dry run counts what the periods saved now would delete. After saving a much shorter period, run one before the real run to see how much the purge will take with it. A dry run of purge-orphan-images reports the objects in the bucket that no image row names and that are at least a day old; after a restore, those include the images uploaded after the backup was taken.

Rebuilding the statistics of a day

The chain never goes back over a day it has finished, so a day's statistics are not rebuilt again when the data behind them is corrected later. To rebuild one, after such a correction or when a release's notes ask for it, run the four links in their order, naming the day in the tenant's own calendar:

docker run --rm -e PUBLIRA_CONTENT_STATS_DB_URL \
  publira/publiractl:<tag> job project-episode-reads
docker run --rm -e PUBLIRA_CONTENT_STATS_DB_URL \
  -e PUBLIRA_CONTENT_STATS_DATE=2026-10-01 \
  publira/publiractl:<tag> job aggregate-content-stats
docker run --rm -e PUBLIRA_CONTENT_STATS_DB_URL \
  publira/publiractl:<tag> job aggregate-rankings
docker run --rm -e PUBLIRA_CONTENT_STATS_DB_URL \
  publira/publiractl:<tag> job build-recommend-features

A run rebuilds that day for every tenant. The rankings and the recommendations are rebuilt here for every tenant's yesterday, since the storefront only shows the newest leaderboard and the weekly one ending yesterday covers the last seven days; give them a date, with PUBLIRA_CONTENT_RANKING_DATE and PUBLIRA_RECOMMEND_FEATURES_DATE, only to rebuild an older leaderboard.

A tenant whose content event retention period no longer covers the day is left out of the run, the same way the worker skips such a day: its analytics events for the day are already gone, so its statistics are kept as they are rather than rebuilt from what is left. So is a tenant whose period was lengthened after the purge had taken the day: a longer period does not bring deleted events back. The run logs each such tenant as skipped and still rebuilds the day for every other tenant.

A run by hand does not move the worker's record of how far each tenant has got, so the worker neither skips nor repeats a day because of it.

Which jobs are safe to repeat

Every job can be run again, and alongside the worker's own pass of it:

JobRunning it again
project-episode-readsWrites nothing once every read is filed
aggregate-content-stats, aggregate-rankings, build-recommend-featuresReplace what they built with the same result. Two runs of one of them for the same tenant and day wait for each other, and the second fails after 30 seconds rather than both writing
Every purge-*Finds nothing left to delete
close-royalty-statementsFinds every owed month already closed. A first run closes for real only the months the next scheduled pass would close: those of tenants on Close automatically whose close day has come
sync-google-play-voided-purchasesTakes back nothing a second time
build-search-indexDoes nothing when no build is due, or when the worker is already building
reconcile-paymentsDoes nothing when no reconciliation is waiting. One the worker is running is not taken up a second time
build-data-exportsDoes nothing when no reader is waiting for a copy. One the worker is preparing is not taken up a second time
erase-tenantsDoes nothing when no tenant is waiting to be erased, or when the worker is erasing one

The one exception is timing: do not run purge-orphan-images or purge-data-exports while a backup of the bucket is being copied, as Backup and restore describes.

The publication, free reading period, day rollover, and pinned announcement jobs have no command of their own. To make them act, get the worker running.