Redis key layout¶
Layout version 1
This page is the contract between the Redis store (the Bellhop.Redis package) and the data it keeps on the server: every key the store writes, its Redis type and what it holds, the rules every script of the store follows, and the commands the store sends. Operators read it to inspect, back up or migrate a store; the store's tests check it, so a key the page does not list fails them.
The layout has a version, which is the Redis store's schema version. The store keeps it in the layout field of the store hash (below). When a node starts with Bellhop:AutoMigrate on, its default, it records the version it expects, and migrates an older one; with it off, a layout more than one version behind fails the start with a message that points here, and so does a layout newer than the node knows. Until the first release of Bellhop.Redis, the layout-1 rows of the job lifecycle structures may still be refined by the changes that first write them; after it, a change to a row is a new layout version.
Composing a key¶
Every key is the prefix, the hash tag {_shared}, the namespace in braces for a key of a namespace, then a colon and the rest:
<prefix>{_shared}{<namespace>}:<rest> a key of one namespace
<prefix>{_shared}:<rest> a store-wide key, of no namespace
<prefix>isRedisStoreOptions.KeyPrefix,bellhop:by default: 1 to 64 printable ASCII characters with no space and no brace. Applications with different prefixes on one server do not see each other's keys._sharedis the hash tag of every key of the store. Redis Cluster hashes a key by the text in its first braces, so all keys of a store, of every namespace and store-wide, are in one hash slot, and one script may touch any of them: the scripts that change a namespace's keys and store-wide state in one step (see "Spanning store-wide keys" below) stay atomic on a Cluster. The tag is the same on every topology, standalone, with Sentinel or a Cluster, so the key names are known before the store connects and a store's data moves between topologies as it is.<namespace>is the node'sBellhop:Namespace,defaultby default, in the braces right after the tag. It is part of the name, not of the tag: two namespaces' keys never meet, as their names differ, but they share the slot. A namespace starts with a letter, so_sharedis never one, and a key whose tag the colon follows is store-wide.- The tag has a cost on a Cluster: a store's keys, all its namespaces' included, are on the one shard that owns the slot of
_shared. The prefix is outside the tag, so anotherKeyPrefixdoes not move a store to another shard: every Bellhop store on a Cluster is on that shard, and the other shards serve the Cluster's other data. Spreading one store over shards is the purpose of ShardByQueue, which a later version adds. - Every other part of a key name, such as a queue name, a node id, a job name, a tag, a unique key, a recurring job name or a dashboard's path, is encoded before it goes into the name:
%becomes%25,:becomes%3A,{becomes%7Band}becomes%7D, and nothing else changes. A part then never holds a colon or a brace, so two parts cannot run into each other (a queuea:working:bis not the working list of queuea) and no part changes the hash tag. A namespace and a job id need no encoding, as they hold none of these characters. In the table below, a placeholder other than<prefix>stands for the encoded part.
The store uses database 0 only. A connection string that names another default database fails the host's start; on a multiplexer the application shares with the store, the store uses database 0 whatever its default. The store never sends SELECT. When an application shares its multiplexer with the store and uses another database on it, StackExchange.Redis itself sends SELECT on that connection to switch between the application's database and database 0 around the store's commands.
Keys¶
Times are whole microseconds since the Unix epoch, from the server's clock, except the dashboard API keys' and launches' times, which the calling node gives ("Dashboard API keys" and "Dashboard launches" below), and the node samples' times, which the node that took each gives ("Node samples" below). A sorted-set score that is a time is exact: such numbers stay below 2^53. A job's sequence number is its place in its namespace's creation order, and every index of jobs is scored by it, so an index pages in creation order. Every member of a set, sorted set or list below is a job id, unless its row says otherwise. Placeholders are in angle brackets; the only braces are the hash tag's and the namespace's.
The rows of the job lifecycle structures were refined by the change that first writes them, within layout version 1, as this page allows: the ready list is one per queue and priority, the indexes are scored by sequence number, tags are entries of the secondary index, a sorted set, the NextRunAt set holds the Active recurring jobs only, the node records are kept 31 days for the rules that watch lost nodes, the finished batches are scored by when they finished rather than by sequence number, so retention reads only the batches that may have expired, and the rows from sequence to alert-rate:<name> below that the first page did not have were added, the dashboard API keys' three rows (api-keys, api-key-names and api-keys:expiring), the node samples' four (node-samples, node-samples:by-time, node-samples:by-node and node-samples:node:<node>), the dashboard launches' two (launch-sequence and launches), the tags in use's two (tag-sequence and tags), each job's set of children (job:<id>:children), the throttle keys' four (concurrency-keys, concurrency:<key>:holders, concurrency:<key>:waiting and rate:<key>:waiting) and the sets of names the dashboard pages by name (recurring-jobs:by-name, api-keys:by-dashboard:<dashboard> and queues:by-name) and the occurrence ids (recurring:<name>:occurrence-ids) among them. The keys of a namespace, first under the namespace as their hash tag, were moved under the store's one tag, with the namespace in braces after it, so the scripts that span store-wide keys run on a Cluster.
| Pattern | Type | Score or value | Written by |
|---|---|---|---|
<prefix>{_shared}{<namespace>}:sequence |
string | the namespace's last job sequence number, taken only by INCR in the scripts that create jobs. A missing counter starts from the call's time in microseconds, or from more when the creating node has seen a higher sequence number or generation marker, written with SET NX PX and an expiry of 100 years, which INCR keeps: after a flush every new id is above every id given before it, so none repeats one a running job still holds. A new namespace's first id is therefore a time, not 1; ids keep their 19 digits until the year 2255. A rollback that brings back a lower counter is not covered | the create script, the recurring scripts that start occurrences |
<prefix>{_shared}{<namespace>}:job:<id> |
hash | one job: its fields, as "The job hash" below lays them out | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:job:<id>:history |
list | the job's transitions, oldest first, each a packed list (below) | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:job:<id>:entries |
set | members: the index sets that list the job, each as the rest of its name after the namespace's braces and colon, such as queue:mail:jobs, and the job's runs in the sets of outcomes, as run:<claim>:<outcome>; it never expires, so retention can trim those sets once the job's hash has expired |
the create, index and add-job-tag scripts, and the scripts that end a run |
<prefix>{_shared}{<namespace>}:job:<id>:log |
list | the job's captured log lines, oldest first, each a packed list (below), and, once the log is marked truncated, the entry truncated after the last of them |
the append-job-log script |
<prefix>{_shared}{<namespace>}:job:<id>:result |
hash | the result of the job's last success: fields json and size, or size and dropped ("1") for a result dropped for its size |
the scripts that end a run |
<prefix>{_shared}{<namespace>}:job:<id>:continuations |
sorted set | the job's continuations that await it; score: the continuation's sequence number. A continuation leaves it when the job's outcome, a cancellation or a deletion moves it; it never expires, so retention can cancel what still awaits once the job's hash has expired | the create script, and the scripts that finish, cancel or remove jobs |
<prefix>{_shared}{<namespace>}:job:<id>:children |
sorted set | index of the jobs created with the job's id as their parent id: continuations, chain steps after the first, and any job created with a parent id; score: the child's sequence number. Each child's entries set lists it, so the child's deletion, its removal by retention, or retention's trim of a child whose hash has expired takes the child out, and the set goes with its last child, also when its parent was removed before it: it holds the children still stored, whether the parent is or not, and never expires | the create script and the recurring scripts that start occurrences, which file each job with a parent id; the remove-jobs script, through the entries set |
<prefix>{_shared}{<namespace>}:queue:<queue>:ready:<priority> |
list | ids of the queue's enqueued jobs of the priority (a decimal integer), in the order they entered Enqueued: the claim takes from the head, a job entering Enqueued goes to the tail. A claim leaves out a queue that is paused or at its limit, reads the other queues' lists in its order, 100 entries a read, and hands its script up to 100 candidates a call (jobs still enqueued whose name it has, one per concurrency key, no LongRunning job while the node is at its limit), calling again with the next candidates while the script takes none; it reads at most 1,000 entries, so more than 1,000 jobs it may not take ahead of one it may hide that one from that claim | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:queue:<queue>:priorities |
sorted set | members: the priorities, as decimal integers, that have a ready list; score: minus the priority, so the highest comes first | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:queue:<queue>:working:<node> |
list | ids a node claimed from the queue and is processing | claim scripts, and the scripts that end a run |
<prefix>{_shared}{<namespace>}:scheduled |
sorted set | score: the job's due time | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:retry |
sorted set | score: the time of the job's next attempt | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:leases |
sorted set | score: the deadline of the job's lease | claim and lease scripts |
<prefix>{_shared}{<namespace>}:enqueued |
sorted set | the enqueued jobs; score: the time the job last entered Enqueued | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:cancel-requested |
sorted set | the processing jobs whose cancellation was requested; score: the job's sequence number | the cancel script, and the scripts that end a run |
<prefix>{_shared}{<namespace>}:state:<state> |
sorted set | index of the jobs in the state (scheduled, enqueued, processing, succeeded, failed, dead-lettered, cancelled, awaiting or unroutable); score: the job's sequence number |
job lifecycle scripts |
<prefix>{_shared}{<namespace>}:finished:<state> |
sorted set | the jobs in a finished state (succeeded, cancelled or dead-lettered), which retention removes; score: the time the job entered the state |
job lifecycle scripts |
<prefix>{_shared}{<namespace>}:queues |
set | members: the names of the queues jobs of the namespace were created in, as they are; the queue depths read the ready lists of each | the create script |
<prefix>{_shared}{<namespace>}:queues:by-name |
sorted set | members: the names queues holds, as they are, each scored 0, so the set keeps them in the byte order of their UTF-8 text; the queues page reads it by rank ("Pages by name" below) |
the create script, the recurring scripts that start occurrences, and recreate-run |
<prefix>{_shared}{<namespace>}:jobs |
sorted set | index of every job of the namespace, which the jobs list pages through when a query names no other index; score: the job's sequence number | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:queue:<queue>:jobs |
sorted set | index of the queue's jobs; score: the job's sequence number | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:name:<name>:jobs |
sorted set | index of the jobs of a job name; score: the job's sequence number | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:unroutable:<name> |
sorted set | the Unroutable jobs of a job name; score: the job's sequence number | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:index:<index>:<value> |
sorted set | the secondary index's entries of an index and a value, a job's tags under the index tag and its correlation id under correlationId among them; score: the job's sequence number, and for an id the store never gave (the index does not check the job exists) its first ten characters counted in base 39 minus 2^53, below every sequence number, so the set's order is the ids' ordinal order within each kind |
the create, index and add-job-tag scripts |
<prefix>{_shared}{<namespace>}:runs:<outcome> |
sorted set | the runs that ended with the outcome, succeeded or failed (an attempt that failed or was interrupted), which the recent counts count; members: the runs' lease tokens; score: the time the run ended. The job's entries set records each as run:<claim>:<outcome>, so the job's removal takes it out |
the scripts that end a run |
<prefix>{_shared}{<namespace>}:batch-sequence |
string | the namespace's last batch sequence number, changed only by INCR in the create script | the create script |
<prefix>{_shared}{<namespace>}:batch:<id> |
hash | one batch: fields seq (its batch sequence number), name, state (the decimal value of BatchState: 0 Open, 1 Succeeded, 2 Completed), created (a time), members (the members it was created with), and the counts of its stored members, succeeded and unfinished, which every script that finishes, requeues or removes a member changes |
the create script, and the scripts that finish, requeue or remove jobs |
<prefix>{_shared}{<namespace>}:batch:<id>:members |
sorted set | the batch's stored members; score: the member's sequence number | the create script, and the scripts that remove jobs |
<prefix>{_shared}{<namespace>}:batch:<id>:continuations |
sorted set | the batch's continuations that await it; score: the continuation's sequence number | the create script, and the scripts that finish, cancel or remove jobs |
<prefix>{_shared}{<namespace>}:batches:finished |
sorted set | the batches that completed or succeeded, which retention removes; members: batch ids; score: the time the batch last finished, or, once a member was removed, the batch's creation time | the create script, and the scripts that finish or remove jobs |
<prefix>{_shared}{<namespace>}:recurring:<name> |
hash | one recurring job's definition, as "Recurring jobs" below lays it out, with the version its latest write gave it |
the write-recurring script |
<prefix>{_shared}{<namespace>}:recurring |
sorted set | members: the names of the Active recurring jobs that have a NextRunAt; score: the job's NextRunAt, so the due jobs are one range read | the write-recurring script |
<prefix>{_shared}{<namespace>}:recurring-jobs |
set | members: the names of every recurring job of the namespace | the write-recurring script |
<prefix>{_shared}{<namespace>}:recurring-jobs:by-name |
sorted set | members: the names recurring-jobs holds, each scored 0, in byte order; the recurring jobs page reads it by rank |
the write-recurring script |
<prefix>{_shared}{<namespace>}:recurring-version |
string | the last version a write gave a recurring job of the namespace, changed only by INCR in the write-recurring script | the write-recurring script |
<prefix>{_shared}{<namespace>}:recurring:<name>:occurrences |
hash | the occurrences of the recurring job with the name, kept after the job is removed: field the occurrence's id, value its record; and, while one waits, field job: and its id, value the job it starts with, packed |
the recurring scripts |
<prefix>{_shared}{<namespace>}:recurring:<name>:occurrence-ids |
sorted set | the ids of every occurrence of the recurring job with the name the occurrences hash holds, kept as long; members and score: the ids, so the newest are one ZRANGE by rank |
the recurring scripts, and recreate-run |
<prefix>{_shared}{<namespace>}:recurring:<name>:waiting |
sorted set | the waiting occurrences of the recurring job with the name; members and score: the occurrences' ids | the recurring scripts |
<prefix>{_shared}{<namespace>}:recurring:<name>:active |
sorted set | the started occurrences of the recurring job with the name whose job is stored and unfinished, Unroutable included; members and score: the occurrences' ids | the recurring scripts, and the scripts that finish, cancel or requeue jobs |
<prefix>{_shared}{<namespace>}:recurring:<name>:outcome |
hash | the last outcome of the recurring job with the name: fields kind (the decimal value of RecurringJobOutcomeKind), occurrence (its id), scheduled (its time), job (its job's id, when it has one), skip (the decimal value of RecurringOccurrenceSkipReason, for a skip) and at (when it was recorded) |
the recurring scripts, and the scripts that finish or cancel jobs |
<prefix>{_shared}{<namespace>}:recurring-waiting |
set | members: the names of the recurring jobs that have a waiting occurrence | the recurring scripts |
<prefix>{_shared}{<namespace>}:occurrence-sequence |
string | the namespace's last occurrence id, taken only by INCR in the recurring scripts; a missing counter starts as sequence does, so after a flush a new occurrence is never taken for an earlier one than a running job's |
the recurring scripts |
<prefix>{_shared}{<namespace>}:miss-sequence |
string | the namespace's last miss record id, changed only by INCR in the write-recurring script | the write-recurring script |
<prefix>{_shared}{<namespace>}:misses |
sorted set | the namespace's miss records; members and score: their ids | the write-recurring and remove-misses scripts |
<prefix>{_shared}{<namespace>}:misses:recorded |
sorted set | the namespace's miss records, which retention removes; members: their ids; score: the time they were recorded | the write-recurring and remove-misses scripts |
<prefix>{_shared}{<namespace>}:misses:records |
hash | the namespace's miss records: field the record's id, value the record, as "Recurring jobs" below lays it out | the write-recurring and remove-misses scripts |
<prefix>{_shared}{<namespace>}:nodes |
sorted set | the node registry; members: node ids; score: the node's last heartbeat. A node whose last heartbeat is older than StaleNodeAge is removed by the next heartbeat of any node, up to 500 such nodes a heartbeat | heartbeat scripts |
<prefix>{_shared}{<namespace>}:node-heartbeats |
sorted set | members: node ids; score: the node's last heartbeat, kept for 31 days after it (the longest NodeLostAfter and a day), also once the registry let the node go, for the rules that watch lost nodes | heartbeat scripts |
<prefix>{_shared}{<namespace>}:node:<node> |
hash | one node's record: fields heartbeat (its last heartbeat), names (the job names it has handlers for, packed), recurring (its recurring jobs, packed as name and hash pairs) and stopped (when it stopped cleanly); it expires 31 days after the node's last heartbeat |
heartbeat scripts |
<prefix>{_shared}{<namespace>}:concurrency:<key>:holders |
sorted set | the namespace's Processing jobs that hold the concurrency key; score: the job's sequence number, so the throttles page lists the first by rank | claim scripts, and the scripts that end a run |
<prefix>{_shared}{<namespace>}:concurrency:<key>:waiting |
sorted set | the namespace's Enqueued jobs of the concurrency key; score: the time the job last entered Enqueued, as in enqueued |
the scripts that move jobs into or out of Enqueued ("Throttle keys" below) |
<prefix>{_shared}{<namespace>}:rate:<key>:waiting |
sorted set | the namespace's Enqueued jobs of the rate-limit key; score: the time the job last entered Enqueued, as in enqueued |
the scripts that move jobs into or out of Enqueued ("Throttle keys" below) |
<prefix>{_shared}{<namespace>}:long-running |
hash | fields: node ids; value: how many LongRunning jobs the node is processing, an integer changed only inside scripts | claim scripts, and the scripts that end a run |
<prefix>{_shared}{<namespace>}:unique:<key> |
string | the id of the job that holds the unique key; written only with SET NX PX, with an expiry of 100 years: the key lives as long as its job holds it, and the script that takes the job out of the active states deletes it | job lifecycle scripts |
<prefix>{_shared}{<namespace>}:generation |
hash | the generation marker, which reveals a flush or a rollback: fields marker (a forward-only value from the server's clock, or 0, the lowest, for the first marker of a server that had none), reconciling (equal to marker while that value is being reconciled, absent otherwise) and last-reset (the time a node last replaced the marker or wrote the first one); one in every namespace the claim scripts use. Only a worker node writes it |
the scripts that begin with Parts/generation.lua |
<prefix>{_shared}{<namespace>}:reset |
hash | the unacknowledged-reset record: the last reset a worker node detected in the namespace, with fields state (unacknowledged or acknowledged), reset (the marker value the replacement wrote, in microseconds by the server's clock) and acknowledged-at (the call's time of the acknowledgement, present only once acknowledged); one per namespace, which a later reset overwrites as unacknowledged. Never written for a first marker or a join |
the scripts that begin with Parts/generation.lua, in the same step as a marker's replacement; reset-record |
<prefix>{_shared}{<namespace>}:api-keys |
hash | the namespace's dashboard API keys, in every state, never removed: field a key's hash (64 lowercase hexadecimal digits, as given), value its record, as "Dashboard API keys" below lays it out | the create-api-key, revoke-api-key and expire-api-keys scripts |
<prefix>{_shared}{<namespace>}:api-key-names |
hash | the names of the namespace's dashboard API keys, in every state, never removed: field a key's name, as it is; value its key hash | the create-api-key script |
<prefix>{_shared}{<namespace>}:api-keys:by-dashboard:<dashboard> |
sorted set | members: the names of the keys created on the dashboard with the path, each scored 0, in byte order, never removed; the API keys page reads it by rank, so it reads no other dashboard's key | the create-api-key script |
<prefix>{_shared}{<namespace>}:api-keys:expiring |
sorted set | the namespace's Active dashboard API keys that have an expiry; members: their key hashes; score: the expiry. A key leaves it when it is revoked or marked expired | the create-api-key, revoke-api-key and expire-api-keys scripts |
<prefix>{_shared}{<namespace>}:node-samples |
hash | the namespace's node metrics samples, kept until a worker node removes them: field a sample's name, its time and its node (<time>:<node>, the node as it is), value its record, as "Node samples" below lays it out |
the write-node-sample and remove-node-samples scripts |
<prefix>{_shared}{<namespace>}:node-samples:by-time |
sorted set | the names of the namespace's node samples; score: when each was taken | the write-node-sample and remove-node-samples scripts |
<prefix>{_shared}{<namespace>}:node-samples:by-node |
sorted set | members: the ids of the nodes with samples; score: when the node's latest sample was taken; the nodes page reads the nodes seen in its window from it | the write-node-sample and remove-node-samples scripts |
<prefix>{_shared}{<namespace>}:node-samples:node:<node> |
sorted set | the names of one node's samples in the namespace; score: when each was taken; a page of nodes reads only its own nodes' samples from them | the write-node-sample and remove-node-samples scripts |
<prefix>{_shared}{<namespace>}:launch-sequence |
string | the namespace's last dashboard launch id, changed only by INCR in the record-launch script | the record-launch script |
<prefix>{_shared}{<namespace>}:launches |
sorted set | the namespace's dashboard launches, the newest the last record kept; members: a launch's id, a colon and its record, as "Dashboard launches" below lays it out; score: the launch's id | the record-launch script |
<prefix>{_shared}{<namespace>}:tag-sequence |
string | the last number a tag of the namespace was given as it came into use, changed only by INCR in the scripts that enter a tag in tags |
the create, index, add-job-tag and recreate-run scripts |
<prefix>{_shared}{<namespace>}:tags |
sorted set | the namespace's tags in use, each while its set index:tag:<value> holds an entry, as "Tags in use" below says; members: the tags, as they are; score: the number the tag counter gave it as it came into use |
the create, index, add-job-tag, recreate-run and remove-jobs scripts |
<prefix>{_shared}:store |
hash | field layout: the layout version, as a decimal string. A reset erases it with the rest of the store, so a worker node records the version it expects again, only where it is missing, when it starts a reconciliation |
the migrate-layout script; the restore-layout script |
<prefix>{_shared}:migration-lock |
string | the token of the node migrating the layout; set with SET NX PX 30000 | the migrating node; deleted by the release-migration-lock script |
<prefix>{_shared}:processing |
hash | the processing controls, shared by every namespace: field maintenance ("1" while the maintenance pause is on), paused:<queue> ("1" while the queue is paused) and limit:<queue> (the queue's concurrency limit), with the queue's name as it is |
the processing-control script |
<prefix>{_shared}:running |
hash | fields: queue names, as they are; value: how many of the queue's jobs are processing, in every namespace, an integer changed only inside scripts | claim scripts, and the scripts that end a run |
<prefix>{_shared}:concurrency:<key> |
string | the number of running jobs of the concurrency key, an integer changed only inside scripts; shared by every namespace | claim and completion scripts |
<prefix>{_shared}:concurrency-keys |
set | members: the concurrency keys, as they are, whose counter concurrency:<key> is above zero: the keys a Processing job of any namespace holds |
claim scripts, and the scripts that end a run |
<prefix>{_shared}:throttles |
hash | the throttle settings, shared by every namespace: field max:<key> (the concurrency key's Max) and rate:<key> (the rate limit, as the limit, the window in microseconds and fixed or sliding, separated by colons), with the key as it is |
the throttle script |
<prefix>{_shared}:recurring-names |
hash | the register of recurring job names, which are unique across the store: field a recurring job's name, as it is; value the namespace that holds it | the write-recurring script |
<prefix>{_shared}:starts:<key> |
sorted set | the recorded starts of a rate-limit key while it has a rate limit; members: the lease tokens of the claims; score: the time of the claim. At most the limit's latest starts are kept | claim scripts |
<prefix>{_shared}:namespaces |
set | members: the namespaces whose stores wrote jobs, recurring jobs or nodes, which the alert rules read; the registration rides on a store's first create, recurring job write or heartbeat, which records the store's own namespace in its own script (a call that writes nothing leaves it to the next) | the create-jobs, write-recurring and record-heartbeat scripts |
<prefix>{_shared}:notifications |
hash | the store-wide notification state, as "Notifications" below lays it out: the notification lease (token, node, expires), the counters tokens, deliveries, cooldowns, events (the last alert event's position) and versions (the last rule version's id), changed only by HINCRBY, and rates (when failure rates began to be counted) |
the notification scripts, and the scripts that log alert events |
<prefix>{_shared}:notification-rules |
hash | the rules last published: fields node, at, rules (packed, as "Notifications" below lays them out) and name:<rule> ("1") for each rule's name, as it is |
the publish-notification-rules script |
<prefix>{_shared}:notification-deliveries |
hash | every notification delivery, as "Notifications" below lays it out: field the delivery's id, zero-padded to 19 digits, and the fields beside it | the notification scripts |
<prefix>{_shared}:notification-delivery-ids |
sorted set | every notification delivery; members: their ids, zero-padded to 19 digits; score: the id | the notification scripts |
<prefix>{_shared}:notification-deliveries:<state> |
sorted set | the notification deliveries in a state (pending, sent, suppressed or failed); members: their ids, zero-padded to 19 digits; score: the id |
the notification scripts |
<prefix>{_shared}:notification-due |
sorted set | the pending notification deliveries; members: their ids, zero-padded to 19 digits, so ties are in id order; score: the time of the next attempt | the notification scripts |
<prefix>{_shared}:notification-tests |
hash | field: a published rule's name, as it is; value: the id of its latest test delivery, which a test request returns while it is pending | the notification scripts |
<prefix>{_shared}:notification-subject-cooldowns |
hash | the subject cooldowns: field a rule's name and a subject, separated by a NUL; value the id of the delivery that opened the cooldown and its end, separated by a colon | the notification scripts |
<prefix>{_shared}:notification-subject-cooldown-ends |
sorted set | the subject cooldowns, which a digest pass drops once their end has passed and they are closed; members: their fields in the subject cooldowns; score: their end | the notification scripts |
<prefix>{_shared}:notification-rule-cooldowns |
hash | the rule cooldowns not yet ended by a digest pass, as "Notifications" below lays them out, and field rule:<rule> (a rule's name, as it is), whose value is the id of the rule's latest |
the notification scripts |
<prefix>{_shared}:notification-rule-cooldown-ends |
sorted set | the rule cooldowns not yet ended by a digest pass; members: their ids; score: their end | the notification scripts |
<prefix>{_shared}:alert-versions |
hash | the versions of the rules that watch events, as "Alert events" below lays them out: field the version's name, trigger, threshold and tolerance, packed; value its record | the evaluate-notification-rule script |
<prefix>{_shared}:alert-events:dead-letters |
sorted set | the dead-letters a rule version still has to read; members: the event's position, namespace and job id, separated by colons; score: the position | end-runs, and the evaluate-notification-rule script |
<prefix>{_shared}:alert-events:failures:<attempt> |
sorted set | the failed attempts of the attempt number a rule version still has to read; members: the event's position, namespace and job id, separated by colons; score: the position | end-runs, and the evaluate-notification-rule script |
<prefix>{_shared}:alert-events:misses |
sorted set | the records of missed instants a rule version still has to read; members: the event's position, namespace, miss record id and recurring job name, separated by colons; score: the position | write-recurring, and the evaluate-notification-rule script |
<prefix>{_shared}:alert-events:starts |
sorted set | the occurrence starts a rule version still has to read; members: the event's position, namespace, job id, occurrence id, lateness in microseconds and recurring job name, separated by colons; score: the position | the recurring scripts, and the evaluate-notification-rule script |
<prefix>{_shared}:alert-readers:dead-letters |
sorted set | the rule versions that read the dead-letters; members: their ids; score: the position each has read up to | the evaluate-notification-rule script |
<prefix>{_shared}:alert-readers:failures:<attempt> |
sorted set | the rule versions that read the failed attempts of the attempt number; members: their ids; score: the position each has read up to | the evaluate-notification-rule script |
<prefix>{_shared}:alert-readers:misses |
sorted set | the rule versions that read the misses; members: their ids; score: the position each has read up to | the evaluate-notification-rule script |
<prefix>{_shared}:alert-readers:starts |
sorted set | the rule versions that read the occurrence starts; members: their ids; score: the position each has read up to | the evaluate-notification-rule script |
<prefix>{_shared}:alert-marks:dead-letters |
sorted set | the dead-letters delivered for a rule name; members: the name and the event's position, separated by a NUL; score: the position | the evaluate-notification-rule script |
<prefix>{_shared}:alert-marks:failures:<attempt> |
sorted set | the failed attempts of the attempt number delivered for a rule name; members: the name and the event's position, separated by a NUL; score: the position | the evaluate-notification-rule script |
<prefix>{_shared}:alert-marks:misses |
sorted set | the misses delivered for a rule name; members: the name and the event's position, separated by a NUL; score: the position | the evaluate-notification-rule script |
<prefix>{_shared}:alert-marks:starts |
sorted set | the occurrence starts delivered for a rule name; members: the name and the event's position, separated by a NUL; score: the position | the evaluate-notification-rule script |
<prefix>{_shared}:alert-marks:nodes |
sorted set | the lost nodes delivered for a rule name; members: the name and the node's namespace, id and last heartbeat (<namespace>:<node>@<heartbeat>), separated by a NUL; score: the heartbeat, dropped 31 days after it |
the evaluate-notification-rule script |
<prefix>{_shared}:alert-rate-totals |
hash | field: a job name, as it is; value: its ended attempts and failed attempts, in every namespace, since failure rates began to be counted, and the minute of their latest change, separated by colons | end-runs |
<prefix>{_shared}:alert-rate:<name> |
sorted set | a job name's ended and failed attempts at the end of each minute they changed in; members: the minute, the attempts and the failures, separated by colons; score: the minute's start. Those older than 30 days are dropped but the latest of them | end-runs |
Keys are created when they are first written: a store on layout version 1 with no job holds the store hash only.
The job hash¶
A job's hash holds one field per value the job has; a missing field is one it does not have. Times are whole microseconds since the Unix epoch and durations are ticks, as decimal strings.
| Field | Value |
|---|---|
seq |
the job's sequence number |
name, queue, priority, payload |
as created |
state |
the state, as the decimal value of JobState: 0 Scheduled, 1 Enqueued, 2 Processing, 3 Succeeded, 4 Failed, 5 DeadLettered, 6 Cancelled, 7 Awaiting, 8 Unroutable |
created, scheduled, retry |
when it was created, the time it was scheduled for, the time of its next attempt |
enqueued, changed |
when it last entered Enqueued, when its latest transition was recorded |
attempt, max-attempts, retry-delays, timeout |
its attempt number, max attempts, retry delays (ticks, separated by commas) and timeout (ticks) |
unique, concurrency, rate-limit, long-running |
its unique key, concurrency key, rate-limit key, and "1" for a LongRunning job |
lease-owner, lease-token, lease-expires, claims |
the node holding its lease, the lease token, the lease's deadline, and how many times it was claimed |
cancel |
"1" once its cancellation was requested |
parent, condition, batch |
the job it continues, its continuation condition (the decimal value of ContinuationCondition), its batch |
traceparent, tracestate, correlation, tags |
its trace context, its correlation id and its tags (packed), in the order they were set, a tag its run added last |
progress, progress-message, progress-attempt, progress-at |
the latest progress its handler reported: the fraction as the round-trip text of a double, the message, the attempt and the store's time of the report |
log-size |
the sum of the sizes of its captured log's lines, in bytes, as the log limit counts them |
p:<key> |
each parameter: the field is p: and the parameter's key, the value its JSON |
detached:<token> |
the detachment of the attempt the claim with the lease token started: 0 Abandoned, 1 LeaseLost |
recurring, occurrence |
for a job a recurring job's occurrence started: the recurring job's name and the occurrence's id |
A packed list is each text as its length in UTF-16 code units, a colon and the text, one after the other, with ~ for a missing text. A history entry is a packed list of the state the job went to, the state it came from, the time, the node, the reason (the decimal value of JobTransitionReason), the failure's exception type, message and stack trace, and, for a claim, the lease token. A captured log line is a packed list of its time as UTC ticks, its offset in minutes, its level (the decimal value of LogLevel), category, message and exception, its attempt, the number of its properties, and each property's key and value.
A lease token is the job's id, a hyphen and the number of the claim, so no two claims of any job share one.
A job's sequence number is taken by INCR of the namespace's sequence counter. Its id is the number as 19 digits in the default namespace, and the 19 digits, a hyphen and the namespace in any other, so ids are unique across the store and their ordinal order is creation order within a namespace.
Retention¶
When a job becomes Succeeded, Cancelled or DeadLettered, the script that moves it gives its hash, history, log and result the same expiry: the retention of that state plus a grace of one hour, in whole seconds, rounded up. The retention pass removes the job at its retention, so its removal is logged and counted and its awaiting continuations are cancelled on time; the expiry is only the safety net for a store that no worker cleans. Any later change of state sets them again, and none of them has an expiry while the hash has none. A requeue out of a finished state writes those keys anew without an expiry, in the same script, and removes the result. A member of a batch that is open or completed gets no expiry, as the batch may still need it; a member that finishes while its batch has succeeded, its last member among them, gets its state's. The members that finished before their batch succeeded keep none: the step that makes the batch succeed touches only the member it moves, and the retention pass removes the others. The job's entries set, its set of awaiting continuations and its entry in finished:<state> never expire. So a job whose hash has expired is still listed by the indexes until the retention pass trims it: the counts read from them with ZCARD (the jobs per state, an index value's jobs, a query's count) include it until then, while the pages of jobs leave it out, as they read each job's hash.
The retention pass, RemoveExpiredJobsAsync, is the janitor: it never waits for an expiry to fire. It reads finished:<state> with ZRANGEBYSCORE ... LIMIT, 500 jobs a page that entered the state before the store's time minus that state's retention, reads their hashes and the states of their batches first, passes over the members of an open or completed batch, and removes each other job whole with the remove-jobs script, as a deletion does, cancelling its awaiting continuations, up to the call's count (the retention duty's CleanupBatchSize, 500). A job whose hash has already expired, which happens only when no worker cleaned for the grace after its retention, is found the same way: the script trims, with ZREM, the index and outcome sets its entries set lists, cancels the continuations that still await it, and deletes what is left of it; it is not returned, as it can no longer be read, and does not count against the call's count, so the call reads on past a page of them. A call ends when it has removed its count, when the sets hold no more expired jobs, or after 10 pages that trimmed jobs, the bound of one call's work; so a call that returns fewer than its count has found no more, unless it trimmed 10 pages, and the duty's next run goes on. RemoveExpiredBatchesAsync reads batches:finished with ZRANGEBYSCORE ... LIMIT up to the store's time minus the shortest retention, as a batch that finished later still holds a member within its retention; it checks each batch's state and unfinished count, then its members' states and times, stopping at the first member still within its retention, reads the members' entries sets and continuations only for a batch it removes, and removes that batch with all its members in one script call.
Recurring jobs¶
A recurring job's hash holds one field per value it has: origin, state, before-orphan (the state before it was orphaned), misfire, overlap, orphan and time-mode as the decimal values of their enums; job (the job name), schedule, time-zone, payload and definition (the definition hash) as they are; run-all and max-queued (MaxRunAllOccurrences and MaxQueuedOccurrences) and override ("1" or "0"); active-from, active-until and next-run as times; and version. Every write that lands replaces the hash whole in one script, with a new version from recurring-version, and a write lands only while the hash still has the version the writer read, so the version stands for its state, NextRunAt and definition together. A trigger also lands only while the maintenance pause is off and the NextRunAt it read has come. An add lands only while no namespace holds the name in {_shared}:recurring-names, and a removal takes the name out of it.
An occurrence's record is its state (0 Waiting, 1 Started, 2 Skipped), its time, its job's id and its skip reason (the decimal value of RecurringOccurrenceSkipReason), separated by colons, each empty when it has none. Occurrence ids come from occurrence-sequence, so they increase in the order the occurrences were created. A new occurrence is decided against the earlier ones the waiting set and the active set name, reading their jobs' states in the same script; the scripts that make an occurrence's job Succeeded, DeadLettered or Cancelled take its occurrence out of the active set and record its outcome, and a requeue puts it back. An occurrence that starts creates its job in the same script, as create-jobs creates one. Each namespace keeps the outcomes of its own occurrences, and reads none while another namespace holds the name in {_shared}:recurring-names: the name's last outcome is then that namespace's. The occurrences hash is never trimmed, so it grows by an entry with every occurrence, about 525,000 a year for a job that runs every minute. The recurring scripts enter each occurrence they create in recurring:<name>:occurrence-ids in the same step, scored by its id, and recreate-run enters the occurrence whose record it writes again; nothing removes them, as nothing removes the records. A read of the job's latest occurrences, which the dashboard's history makes on each refresh of the job's page, is one ZRANGE by rank of the newest ids and one HMGET of their records, never the whole hash. The ids came within layout version 1, after the hash: the occurrences an earlier build of the layout created are not in them, so the history leaves them out, and the store runs no backfill, as Bellhop.Redis was not released before them and a store of a released version never lacks them; the history shows every occurrence created after the upgrade. A full read of the occurrences, GetOccurrencesAsync, still loads the hash whole with HGETALL, as its contract asks for every occurrence; no dashboard page or duty makes it.
A miss record is the time it was recorded, its occurrences, each as its id, a colon and its record, separated by commas, and the recurring job's name, the first and last instants missed, how many were missed and dropped, and what dropped them (the decimal value of RecurringMissDropReason), packed, the three parts separated by semicolons. Miss ids come from miss-sequence. The retention pass of miss records reads misses:recorded with ZRANGEBYSCORE ... LIMIT and removes each record still there with the remove-misses script.
Notifications¶
The notification lease, the published rules, the deliveries and their cooldowns belong to no namespace: they are store-wide keys, so a lease held through one namespace's store blocks every other. Every write under the lease is one script that checks the lease in the notifications hash in the same step: held while its token is the writer's and its expires is at or after the call's time. A take writes a new token, the next of the tokens counter zero-padded to 19 digits, which no job's lease token, holding a hyphen, can equal; a release deletes the three fields.
The rules field of the rules hash is a packed list of the rules in name order, each a packed list of its name, trigger (the decimal value of NotificationTrigger), channel, threshold (the round-trip text of a double), window, tolerance (ticks), template, cooldown (ticks), origin (the decimal value of NotificationRuleOrigin) and "1" when it overrides configuration, a missing value as ~.
A delivery's field, its id zero-padded to 19 digits, holds its state (the decimal value of NotificationDeliveryState: 0 Pending, 1 Sent, 2 Suppressed, 3 Failed), attempts, creation time, time of its last write, time of its next attempt, flags (t a test, d a digest, c suppressed by the cap) and the id of the rule cooldown it was created Pending in, or nothing, separated by colons. Beside it are <id>:rule, <id>:subject, <id>:node, <id>:error (only once an update gave one) and, for a digest, <id>:digest: the deliveries the cap suppressed, their distinct subjects, then up to 100 of those subjects, in the order each was first suppressed, packed as the published rules are. No text a store keeps holds a NUL. Deliveries are kept for good, as the other stores keep them.
A rule cooldown's field, its id from the cooldowns counter, holds its end, the deliveries created Pending in it, those of them still pending, the deliveries its cap suppressed and their distinct subjects, separated by colons; beside it are <id>:rule, <id>:s:<n> (the n-th distinct subject the cap suppressed) and <id>:c:<subject> (that subject's n), with the subject as it is. A digest pass reads up to 500 rule cooldowns whose end has come, ends those with nothing created in them still pending, oldest first, each with its digest, and removes their fields; it also drops up to 500 subject cooldowns past their end that are closed.
Alert events¶
The events the alert rules watch are logged, store-wide, by the script whose transition makes them, in the same step: end-runs logs each transition into DeadLettered and each failed attempt (an end by retry or dead; a lease's expiry, a release and a cancellation fail no attempt) in the log of its attempt number; write-recurring each record of missed instants; and the recurring scripts each occurrence's start, with how long after its due time its job was created. An event's position is the next of the events counter. An event is logged only while a rule version reads its log, which its readers set says, and a log keeps at most its latest 100,000 events: a version that falls further behind, or that comes back after an edit or a removal that many events later, does not alert the oldest.
A rule version's record is its id, its position among its events (dead-letters, failed attempts or misses), its position among occurrence starts, and the heartbeat and node it has read lost nodes up to (no node: every node at that heartbeat), separated by colons, the node last. Its first evaluation records it at the events counter's present and the heartbeat of a node lost by now, and enters it in the readers of its logs. A later evaluation reads its events after its positions, at most MaxFirings of each log, and whether each one's job, miss record and occurrence are still stored, across every namespace; the evaluate-notification-rule script then checks the lease and that the version's record is still the one read (STALE otherwise), fires each event not yet marked for the rule's name, marks it, and moves the version on: to the last event read when the page was full, else to the events counter as read before the events. It then drops from each log what every version reading it has read past, and the marks of events no longer logged. Versions are never removed.
Lost nodes have no log: an evaluation reads each namespace's node-heartbeats between the version's point and the store's time less NodeLostAfter, and leaves out a node whose record holds stopped. The heartbeat keeps those for 31 days after a node's last heartbeat, the longest NodeLostAfter and a day, long after the registry let the node go.
The conditions are read again at every evaluation, from every namespace {_shared}:namespaces names: the queues' ready lists; the throttles, {_shared}:concurrency-keys with each key's running count, and the starts of each rate-limit key with a rate limit, then, for each key at its limit, each namespace's concurrency:<key>:waiting or rate:<key>:waiting ("Throttle keys" above); the NextRunAt set and waiting occurrences; and the failure-rate counts. end-runs counts each success and failed attempt per job name and minute from the first evaluation of a failure rate on, so a window is counted in whole minutes and may start up to a minute late. A key at its limit is starved when a namespace's set of its waiting jobs holds one that entered Enqueued before the tolerance in a queue that is not paused: with no queue paused, one ZRANGEBYSCORE ... LIMIT of a single entry decides; with one paused, the store reads the oldest of those jobs' queues in steps of 1,000, up to 10,000 jobs of the key in each namespace, so a key whose late jobs all wait behind 10,000 of its own in paused queues is not seen as starved. The settings and the keys held bound the keys judged, never the jobs.
Lists¶
The jobs list and the dead letters to requeue are read from the index sets, never with KEYS or SCAN. A page reads one set, the one of the query's index criteria (state, names, queue, tag, correlation id, parent) with the fewest entries by ZCARD, or jobs when the query has none; the names of a query read as one set, the union of their indexes, and a parent as job:<parent>:children, so the dashboard's page of a job reads one page of its children whatever the namespace holds. It reads the set in bounded ZRANGE ... BYSCORE [REV] LIMIT steps of at most a page, from the sequence number of the page's cursor, reads the hashes of the jobs a step names, and checks every other criterion on them: the state, names, queue, parent and times on the hash, a tag or correlation id by the job's score in its set. Steps go on until the page is full or the set ends. A job id's ordinal order is its sequence order, so a cursor that is not a stored id still starts the page at the right place.
job:<id>:children came within layout version 1, after the jobs it lists: a child an earlier build of the layout created is not in its parent's set, so a query by its parent leaves it out. Bellhop.Redis was not released before the set, so a store of a released version never lacks it, and the store runs no backfill and no fallback to the hash check alone. A reset erases the sets with the jobs they list.
Tags in use¶
The tags page reads the tags of a namespace from tags, not from the index sets, which the store never enumerates. A script that files a job under a tag, in index:tag:<value>, enters the tag in tags in the same step when it is not there, scored by the next number INCR of tag-sequence gives, so no two tags share a score and a tag keeps its score while it stays in use: the scripts that create jobs (create-jobs, and the recurring scripts that start occurrences), add-job-tag, set-index-entry for an entry of the index tag, and recreate-run, which files a re-created run under its tags again. A script that takes an entry out of index:tag:<value> takes the tag out of tags in the same step when the set is left empty: remove-jobs, for a deletion, retention's removal and trim, and a batch's removal, and set-index-entry for a removal from the index tag. No other script changes the tag sets. Both keys are the namespace's, so none of these scripts spans store-wide keys for them. A job filed under a tag takes the two keys in the script's KEYS; a job with no tag takes neither.
tags and tag-sequence came within layout version 1, after the index sets they list: an index set that a node of an earlier build of the layout wrote holds tags that are not in tags, and the tags page leaves them out until a job created, tagged or filed under the tag after the upgrade enters it again, or their jobs go. Bellhop.Redis was not released before them, so a store of a released version never lacks them. A reset erases both with the index sets, and the counter starts again from 1 with the tags its first writes enter.
A page of tags is one ZRANGEBYSCORE ... LIMIT read of tags after the score of the page before's last tag, which is the page's cursor, a decimal number; a tag keeps its score while it stays in use, so a tag in use the whole time a caller pages is read once, and a tag that left and came back is read again under its new score. Each tag's jobs are one ZCARD of its set, and its succeeded and dead-lettered jobs are counted by reading the set in ZRANGEBYSCORE ... LIMIT steps of 100 entries, each followed by an HGET of every entry's job state: a tag's counts are not read from one consistent state, as a page of the jobs list is not, so a job that changes state, or comes or goes, while its tag is counted may be counted before its change, after it, or not at all. A job whose hash expired before retention removed it counts among the tag's jobs only, as it does in an index's ZCARD.
Throttle keys¶
The throttles page lists the keys of {_shared}:throttles and of {_shared}:concurrency-keys, the concurrency keys a Processing job of any namespace holds, each read whole with HGETALL and SMEMBERS: the operators' settings and the keys held right now bound them, as a Processing job holds at most one key. The store orders the keys ordinally and reads only the page's keys further, side by side: a key's running count is its counter {_shared}:concurrency:<key>; its holders are the first ranks of the store namespace's concurrency:<key>:holders, which is in id order; its waiting jobs are the ZCARD of the namespace's concurrency:<key>:waiting, and the time the longest-waiting of them entered Enqueued is the score of its first rank. The page reads no job and no other set. The reads are several round trips, so they are not one consistent state.
The sets are kept by the scripts that change what they mirror, in the same step. claim-job takes a job it claims out of its keys' waiting sets and, as it increments the key's counter, enters the job in the key's holders and the key in concurrency-keys; end-runs, as it decrements the counter, takes the job out of holders, takes the key out of concurrency-keys when the counter reaches zero and is deleted, and enters a job it hands back or takes back from an expired lease in its keys' waiting sets; recreate-run enters a re-created run as a claim does. Every other script that moves a job into Enqueued enters it in its keys' waiting sets with the score it gives it in enqueued: the scripts that create jobs (through Parts/create.lua), enqueue-jobs, requeue-job, and Parts/resolve.lua for the continuations and batch continuations it releases; and every one that moves a job out of Enqueued takes it out: Parts/cancel.lua, remove-jobs and mark-unroutable. A job's concurrency key and rate-limit key never change, so the store reads them with the fields it reads to name the job's other keys and passes the sets' KEYS positions, 0 for a key the job lacks. A job without a key costs nothing more; a job with one costs a ZADD or ZREM per set it enters or leaves, each O(log n) in the size of its key's set: a claim adds a ZREM per waiting set, a ZADD and an SADD, an end of a run a ZREM, and an SREM as the key's last run ends, and every enqueue or dequeue a ZADD or ZREM per waiting set.
The four sets came within layout version 1, after the jobs they list: on a store an earlier build of the layout wrote, a key held then is missing from concurrency-keys and a job enqueued or processing then is missing from its key's sets, until the job moves, so the page may leave out such a key, list it without its holders, or count fewer jobs waiting, until those jobs are claimed or their runs end. Bellhop.Redis was not released before them, so a store of a released version never lacks them, and the store runs no backfill. A reset erases them with the rest of the store, with the jobs they list.
Pages by name¶
The dashboard's recurring jobs, API keys and queues pages read the namespace's names from the sets of names, recurring-jobs:by-name, the dashboard's own api-keys:by-dashboard:<dashboard> and queues:by-name, whose members all score 0, so Redis keeps them in the byte order of their UTF-8 text, which is Unicode code point order: it differs from ordinal order only between a character from U+E000 to U+FFFF and one beyond U+FFFF. The store sends no ZRANGEBYLEX, so a page is read by rank, by the page-names script: a binary search over the set's ranks finds the first name after the page's cursor, each step one ZRANGE of a single member compared with the cursor byte by byte, and one ZRANGE by rank then reads the page. The search and the read are one script, so they see one state of the set: a name in the set the whole time a caller pages is read once, and a cursor need not be a name in the set. The store then reads the page's records in one more round trip: the recurring jobs' hashes, the keys' hashes from api-key-names and their records from api-keys with an HMGET each, or the queues' depths from their ready lists, as the queue depths read them. A name whose record is gone and a queue with no enqueued job and no setting are passed over, and the store reads on from the step's last name until the page is full or the set ends. The queues page merges into each step the queues that have a setting, read from {_shared}:processing with one HGETALL, which the operators' settings bound, as the processing controls are read.
Each set is kept by the script that keeps the set or hash it mirrors, in the same step: write-recurring adds and removes a job's name with recurring-jobs; create-api-key adds a key's name to its dashboard's api-keys:by-dashboard:<dashboard>, which no script removes, as keys are never removed; and the scripts that create jobs (create-jobs, and the recurring scripts that start occurrences) and recreate-run add a job's queue with queues. The samples of a page's nodes are read from each node's own node-samples:node:<node> (Node samples below), never from every node's. The nodes page pages the nodes seen in its window instead: it reads the namespace's node-heartbeats and node-samples:by-node from the window's start in ZRANGEBYSCORE ... LIMIT steps of at most 1,000, every node seen in the window, which the deployment's nodes bound, chooses the page among them by code point, and reads the page's node records. The overview's latest heartbeat is one ZRANGE of the registry's last rank.
The three sets came within layout version 1, after the keys they mirror: a store written by an earlier build of the layout lacks the names that build wrote until a later write enters them, a recurring job's next write (a trigger, an edit, a pause or a reconciliation) or the next job created in a queue; an API key created by such a build is never entered, as no script writes a key's name again. Bellhop.Redis was not released before them, so a store of a released version never lacks them, and the store runs no backfill. A reset erases them with the rest of the store, and the writes after it enter the names again.
Dashboard API keys¶
A dashboard API key's record is its state (the decimal value of ApiKeyState: 0 Active, 1 Revoked, 2 Expired), its scope (the decimal value of ApiKeyScope: 0 View, 1 Operate), its creation time, its expiry (empty for a key that never expires), its name, its dashboard and its creator, separated by colons. The dashboard is the path of the dashboard the key was created on, the only one it authenticates on ("/jobs", or "/" at the root), percent-encoded as RFC 3986 encodes data (every character but the unreserved ones, UTF-8 bytes as %XX), so it holds no colon: "/jobs" is %2Fjobs. The creator comes last and is the rest of the record, colons included. The key itself is never stored, only its hash, the field the record is kept under. The times are the calling node's, as the store contract gives them, not the server's: whole microseconds since the Unix epoch, a finer part dropped, so an expiry is judged at that resolution.
create-api-key checks the names hash and the records hash and writes both, with the key's place in api-keys:expiring when it has an expiry, in one step, so of two creates with one name or one hash only one stores its key. revoke-api-key reads the name's hash and its record and replaces the record's state, Active to Revoked, in one step. expire-api-keys reads the members of api-keys:expiring scored up to the time the calling node gives, marks each Active one Expired and takes them out, in one step: the set holds only Active keys that expire, so the call reads neither a key that never expires nor a revoked or expired one. A lookup by hash is one HGET of the records hash, and the list one HGETALL of it, one consistent state, which the store orders by name, ordinally.
A reset takes the keys with the rest of the store: they stop authenticating, and operators create new ones; nodes keep no copy to write back. A rollback to an older copy brings the keys back as that copy holds them: a key revoked or created after the copy was taken is Active again, or gone.
Node samples¶
A node metrics sample is named by when its node took it, by that node's clock, and the node's id: <time>:<node>, the time first, as the node may hold colons. Its record is its processor share, its working set, its GC heap, its thread-pool queue length, its jobs in flight, its worker's concurrency and its worker utilisation, separated by colons, each a decimal integer: the two shares as the 64 bits of their IEEE 754 doubles, so they read back exactly, and the two worker figures empty for a node without the worker. The time is the node's, as the store contract gives it, not the server's: whole microseconds since the Unix epoch, a finer part dropped, so two samples of a node within one microsecond are one sample.
write-node-sample checks the samples hash for the sample's name and writes its record, its place in node-samples:by-time and in its node's node-samples:node:<node>, and its node's score in node-samples:by-node when the sample is the node's latest, in one step, so a write retried after it landed, or two writes of one node and time at once, store it once. The store reads the names of node-samples:by-time scored before the time the calling node gives with ZRANGEBYSCORE ... LIMIT, at most 500, and passes each with its node's node-samples:node:<node> to remove-node-samples, which removes each still scored before the time from the three keys, and up to 500 nodes of node-samples:by-node whose latest sample was taken before the time, in one step: a sample another removal took meanwhile is passed over, so of removals at once each removes samples the others do not. The store reads and calls again until it has removed as many as it was asked or a read finds fewer. A read of every node's samples reads node-samples:by-time from its time in bounded ZRANGEBYSCORE ... LIMIT steps of at most 500, each followed by one HMGET of the records it names, and leaves out a sample a removal took between the two; a read of the samples of a page's nodes reads each node's node-samples:node:<node> in the same steps, side by side. The store orders the samples by node, ordinally, and then by time.
The sets of each node's samples came within layout version 1, after the samples: a sample an earlier build of the layout wrote is not in its node's set, so the nodes page does not show it, while the removal still removes it by time. Bellhop.Redis was not released before them, so the store runs no backfill; such samples age out with the samples' retention, and the nodes' samples after the upgrade fill the page.
A reset takes the samples with the rest of the store, and the nodes' next samples start the history again; a rollback brings them back as the copy holds them.
Dashboard launches¶
A dashboard launch's record is its kind (the decimal value of LaunchKind: 0 RunNow, 1 Schedule, 2 Recurring; a reader takes any integer, as a newer version may add a kind), its launch time, the id of the job it created (missing for a recurring launch), the name of the recurring job it added (missing for any other), the job type's name and the principal name of the operator who launched it, packed: each as its length in UTF-16 code units, a colon and the text, with ~ for a missing one, since names and principals may hold colons. The member of launches is the launch's id, a colon and the record, so two launches with the same record are two members. The launch time is the calling node's, as the store contract gives it, not the server's: whole microseconds since the Unix epoch, a finer part dropped.
record-launch draws the id with INCR of launch-sequence, adds the member scored by the id, reads the newest launch past the number the call keeps with one ZRANGE ... BYSCORE REV LIMIT, whose offset is that number, and removes it and every older one with one ZREMRANGEBYSCORE, in one step, so what is left is the newest it keeps, whatever ids they hold. The list is one ZRANGE ... BYSCORE REV LIMIT read of launches, one consistent state, newest first. A launch names its job by id and nothing more: deleting the job or removing it by retention leaves the launch.
A reset takes the launches and their counter with the rest of the store, so ids start again at 1; a rollback to an older copy brings both back as that copy holds them.
Script rules¶
Every script of the store is a file under src/Bellhop.Redis/Scripts, embedded in the assembly, and follows these rules.
- Time from the caller. ARGV[1] is the time of the store call, read with one TIME from the server that runs the script, as a decimal string of microseconds. A script never calls TIME and never uses a node's clock, so it is deterministic: run twice on the same data with the same KEYS and ARGV, it makes the same writes and returns the same reply. The one exception is the dashboard API keys, whose times the store contract has the calling node give, as that node's clock decides whether a key authenticates:
create-api-keystores the creation and expiry it is given, andexpire-api-keysjudges the expiries by the time it is given in ARGV[2], each still with the call's time in ARGV[1]. So are the node samples, which carry the times their nodes took them:write-node-samplestores the time it is given as its score, andremove-node-samplesjudges the samples by the time it is given in ARGV[2]. Likewiserecord-launchstores the launch time it is given, inside a record it never reads. - Declared keys. Every key a script reads or writes is in its KEYS, and all KEYS of one call share one hash tag,
_shared. They are the keys of one namespace or store-wide keys; a script that spans store-wide keys (below) may take both, and no call takes the keys of two namespaces. A script builds no key name of its own, so the store reads what it needs to name a call's keys first, and the script checks that what it was given still holds. - Spanning store-wide keys. A script that must check or change store-wide state atomically with a namespace's keys, such as a claim that counts a concurrency key's running jobs across every namespace, is declared to span store-wide keys where the store loads it: its KEYS hold one namespace's keys and store-wide keys, and no other script's may. Every key of the store has the one hash tag, so such a call is in one slot and atomic on every topology, a Cluster included. The spanning scripts are
claim-job, which reads the processing controls, the queues' running counts, the throttles, the concurrency counters and the rate-limit starts, and enters the key it takes in the concurrency keys held, in the step that claims;end-runs, which frees a run's slot in the running counts and its concurrency counter, and takes the key out of the concurrency keys held as its last run ends, in the step that ends it;write-recurring, which reads and writes the register of recurring job names, unique across the store, in the step that adds or removes a recurring job, and reads the maintenance pause in the step that triggers one;decide-occurrences, which logs each occurrence it starts in the store-wide alert log of occurrence starts in the step that starts it;recreate-run, which counts a re-created run again in the running counts, its concurrency counter and the concurrency keys held in the step that writes its record; andcreate-jobsandrecord-heartbeat, which, likewrite-recurring, record the store's namespace in the register of namespaces in the step of its first create, heartbeat or recurring job write, so that write stays one script; a store's later calls of the three leave the register out of their KEYS.end-runsalso logs the dead-letters and failed attempts it makes in the store-wide alert logs and counts the failure rates, andwrite-recurringthe misses and occurrence starts it makes, in the same step. Every other script keeps to one side: the layout, control, throttle and notification scripts to store-wide keys, the rest to their namespace's. - Reading first. A script answers
STALE, having changed nothing but the generation marker and the reset record (below), when what the store read to name its keys has changed, such as a unique key's holder, the sequence number a create named its id slots from, the tags a tag is added to, the live nodes, the continuations and batches a transition resolves, a recurring job's waiting and active occurrences, or the record of the alert rule version an evaluation read; the store then reads again and calls it again, in the same store call with the same time, and changes nothing in between. - Resolution in the same step. A script that makes a job Succeeded, DeadLettered or Cancelled, or removes one (
end-runs,cancel-job,remove-jobs), resolves the job's awaiting continuations, all the way down a cancellation, and moves the batch of a member by its counts, releasing the batch continuations its new state releases, before it returns. The store reads first, a level of the tree at a time, each awaiting continuation's queue, priority, condition and unique key and its own awaiting continuations, and each batch's awaiting continuations, and passes them to the script, which checks every set it was told about still holds exactly what was read.requeue-jobcounts a requeued member as unfinished in its batch again;create-jobsdecides a continuation's state from its parent's in the step that stores it, and creates a batch and its jobs in one call. - Parts. Code several scripts share is a part under
src/Bellhop.Redis/Scripts/Parts, embedded in the assembly; a script that uses one begins with it, so what the server runs and the SHA1 it is called by are the part's source followed by the script's.Parts/resolve.lua, the resolution above, beginscancel-jobandremove-jobs, and followsParts/generation.luainend-runs,write-recurring,decide-occurrencesandrecreate-run;Parts/outcome.lua, which records a recurring job's last outcome and keeps its active set, follows it in those that finish or cancel jobs and beginsrequeue-job;Parts/cancel.lua, which cancels a job from a record of its keys ascancel-jobdoes, follows them incancel-job, the two recurring scripts andrecreate-run;Parts/create.lua, which writes a new job from its create record, beginscreate-jobsand follows them in the recurring scripts;Parts/alert.lua, which logs the events alert rules watch and counts the failure rates, follows them inend-runsand comes beforeParts/occur.luain the recurring scripts;Parts/occur.lua, which decides a recurring job's occurrences, comes last in the recurring scripts;Parts/notify.lua, which checks the notification lease and writes deliveries as their cooldowns decide, beginspublish-notification-rules,write-notification-deliveryandevaluate-notification-rule; andParts/generation.lua, which reads the generation marker, comes first inclaim-job,renew-lease,end-runs,write-recurring,decide-occurrences,generationandrecreate-run. - The generation marker. A script that begins with
Parts/generation.luatakes its four arguments last: the KEYS positions of the namespace's generation hash and of its reset record, the last marker value the node saw (''for none) and1when the node runs the worker (''otherwise); it reads the marker before its own effect and answers{the generation read, its own reply}, where the read is the marker, the reconciling value and the last reset (''when absent) and what it wrote:initialised,resetor''. Only for a worker does it write, in the same step as the read: a missing marker of a node that saw none becomes the first marker, 0, flagged as reconciling, with the call's time aslast-reset; a missing marker, or one older than the value seen, flagged or not, becomes the call's time, or one more than the value seen when the server's clock is behind it, as the marker, the reconciling value andlast-reset, and in the same step records the reset as unacknowledged in the reset record (stateunacknowledged,resetthe new value,acknowledged-atremoved), so a reply lost after the script ran cannot hide it; the first marker and a join record nothing. The part'sresetSincetells a script that acts on a run whether the store was reset since the run's claim, on its own read: the marker missing or flagged, replaced or written by that read, older than the marker the claim read, with alast-resetlater than the one the claim read, or the node reporting that it detected, joined or initialised a reconciliation since the claim. While the marker is missing or flagged,claim-jobclaims nothing (for one given job it answersRECONCILING), a trigger ofwrite-recurringloses as it does to another write, anddecide-occurrencesanswersRECONCILINGand starts, creates and skips nothing;renew-lease,end-runsand the other recurring writes act as usual.renew-leaseanswersMISSINGin place of a deadline, andset-job-progressanswersMISSINGin place of 0, when the job's hash does not exist: the only answers after which the store may runrecreate-run. Thegenerationscript reads the marker (read), moves an unflagged marker that still holds the value the node saw to the call's time, leavinglast-reset(advance), or removes the flag while the marker still holds the value the node reconciles (clear). The node decides by the server's clock: a worker clears once it has re-seeded andLeaseDurationhas passed since its re-seeding started, and advances a marker unchanged forRecurringReconcileInterval. A reset also erases the layout version in{_shared}:store, which no other write records again before a start migrates, so every node would report the store's schema as version 0 until then: when a reply starts a reconciliation on a worker node (a reset, a first marker or a join), the node runsrestore-layoutbefore the call returns, which records the version the node expects only where the field is missing and leaves a present one, older or newer, for a migration to judge (the command baseline has no HSETNX, so the script reads it first). A restore that fails is logged (LayoutVersionNotRestored) and runs again with the node's next duties, at a claim or a heartbeat; once one succeeds, the node runs it no more until its next reconciliation starts. - The reset record.
reset-recordkeeps{_shared}{<namespace>}:resetonce the generation part wrote it.check, run after each node heartbeat by a worker node that remembers a reset it detected, with that reset's value, writes the record again as unacknowledged when it is missing or holds an older reset (a loss no node detected), and answersrewritten; answersacknowledgedwhen the record holds that reset or a later one, acknowledged, and the node forgets the reset; andunacknowledgedotherwise.acknowledge, run by the dashboard's acknowledgement (POST {path}/api/store/reset/acknowledge, from any node) with the reset the operator saw, answersnonewithout a record,otherwhen the record holds another reset andalreadywhen it is acknowledged; otherwise it setsstatetoacknowledgedandacknowledged-atto the call's time and answersacknowledged. Every answer carries the record'sstate,resetandacknowledged-atas the call read or left them. An acknowledgement covers every reset recorded before it, as the record is one per namespace. - Re-creating a run's record. A node remembers every run it claimed, by lease token: the job's hash as the claim script left it, the marker and
last-resetthe claim read, and the lease deadline as last renewed, until an end of the run gets a reply. When a lease renewal or a progress write of such a run answersMISSING, the store runsrecreate-runin moderun. While the hash is still missing, the marker is missing or flagged,resetSinceholds and the run's lease deadline has not passed by the call's time, it writes the hash again from the claim, Processing under the run's token with its lease renewed (a progress write keeps the deadline) andchangedthe call's time, and puts the job back in every structure a Processing job is in:leases,state:processing, the node's working list,{_shared}:running, its concurrency counter,long-running,queues, the index entries the create script files a job under (jobs, its queue's and its name's index, its tags and its correlation id, with its entries set), and, for an occurrence's job, its record in the occurrences hash (1:<the job's creation>:<id>:, as the hash does not keep the occurrence's time) and the active set. It needs no counter: a counter the reset erased starts again above every number given before (sequence), so no job created later takes the run's id and no later occurrence counts as earlier than its own. It leaves out what the reset erased with nothing to restore it from, or what is stale: the history (empty until the run ends),batch,parent,condition, the progress fields,cancel, thedetached:fields, the rate-limit start and the secondary index entries other than tags and correlation id. A run with a unique key takes it back: a holder that is Scheduled, Enqueued, Awaiting or Unroutable was created during the pause and never ran, and is cancelled in the same script, with reasonDuplicateAfterReset, throughParts/cancel.luawith the cancel record and resolution blockcancel-jobbuilds; a finished or missing holder gives the key up; a Processing or Failed holder, still active and not one to cancel, keeps it, and the script refuses the re-creation (REFUSED), writing nothing but the generation marker and the reset record, so the run is treated as any run whose record is gone and two active jobs never hold one key. Such a holder was claimed while the store was Ready, after an erasure outside a reset (a delete by hand or an eviction) took the run's hash, before the reset that let the run re-assert. The store reads the holder first and passes it; the script answersSTALEwhen the key's holder or what the cancellation resolves changed since, and the store reads again. Its answer isPRESENTwhen the hash exists (the store renews or writes once more),REFUSEDwhen the conditions do not hold or an active holder keeps the unique key (the renewal answers no deadline and the progress write false, as for a run that no longer holds the job), or{the new deadline, {} or {the cancelled holder's id, cancel.job's reply}}. Modeoutcomeruns when such a run ends by success, failure or cancellation and finds the hash missing (a hand-back at shutdown writes nothing): while the hash is still missing andresetSinceholds, it writes a minimal record from the claim, with the end's parameters: Succeeded, DeadLettered for any failure, never retried, or Cancelled; one history entry from Processing that names the finishing node and reasonRecreatedAfterResetwith a failure's details; the state's index and finished set; the index entries above; and the state's expiry on the hash and history. It holds no unique key or concurrency slot and keeps no lease fields, result, continuation, batch, occurrence outcome, alert event or failure-rate count. It answersPRESENT, after which the run ends as usual,REFUSED, after which the end is refused as for a stale token, or the record's fields and values. - Loading. The store calls a script with EVALSHA and the SHA1 of its source. When the server answers NOSCRIPT, after a restart, a failover or SCRIPT FLUSH, the store sends EVAL with the source, which caches it on that server again, and goes back to EVALSHA on the next call.
- Lua. The common subset of Lua 5.1 and 5.4: no
bit,cjson,cmsgpack,redis.replicate_commandsorredis.setresp, nounpackortable.unpack,setfenv,getfenv,loadstringorload, nogoto,//, bitwise operators,utf8orstring.pack. A command name is a string literal inredis.call('NAME', ...)orredis.pcall. - Numbers as strings. Every number passed to a script is a decimal string in ARGV, and a script stores and returns numbers as decimal integer strings, never floats: Lua 5.1 and 5.4 print a float differently.
- Short. A call touches a bounded number of entries, never one proportional to the store's size: no loop over a whole set or list, and a loop is bounded by a count passed in ARGV, at most 500. Some loops are bounded by what one job, one batch or one call holds instead, as the contract makes each one step: a bulk create, a chain or a batch stores all of its jobs in one call, as the contract makes it all or nothing; a requeue writes a finished job's hash, history and log anew without their expiry; a run that replaces a job's parameters removes the old ones from its hash; a transition resolves every awaiting continuation of the job it finishes or removes, all the way down, and every batch continuation its batch releases or cancels; a batch's removal removes all of its members; a trigger decides all of its occurrences, up to a RunAll job's MaxRunAllOccurrences, as the contract makes the write one step; a recurring script reads the recurring job's waiting occurrences and its started ones whose job is unfinished, which its jobs in flight bound; an evaluation of an alert rule fires at most MaxFirings (up to 1,000) events or lost nodes of each kind it reads and the condition's subjects the store read; a digest pass removes the capped subjects of each rule cooldown it ends;
mark-unroutablecompares every live node of the namespace the store read, which the deployment's nodes bound;expire-api-keysmarks every Active dashboard API key of the namespace whose expiry has come, read with ZRANGEBYSCORE without LIMIT, as the contract makes the marking one step, which the keys operators created bound;page-namessearches a set of names in as many steps as the count of its members has bits, each comparing the cursor with one name byte by byte; andrecord-launchfinds the launches past the newest it keeps with one ZRANGE whose LIMIT offset is the number it keeps, at most 10,000, and removes them with one ZREMRANGEBYSCORE, one launch when every call keeps the same number, and at most the 10,000 a call may keep when a call keeps fewer than the one before.
Channels¶
The store publishes on these channels and its nodes subscribe to them, with SUBSCRIBE only: a node that waits for work still polls, so a lost message costs one poll at most.
| Channel | Published when |
|---|---|
<prefix>{_shared}{<namespace>}:queue:<queue>:wake |
a job of the queue enters Enqueued |
<prefix>{_shared}{<namespace>}:wake |
a job of the namespace enters Enqueued, for a node that has claimed nothing yet and so does not know its queues |
<prefix>{_shared}:controls |
a change of the processing controls or throttles may admit claims they refused: a queue resumed, a limit raised or removed, the maintenance pause turned off, a Max raised, a rate limit removed or loosened, or a run ended that held a concurrency key or a slot of a queue's limit |
A node subscribes to the wake channels of the queues it has claimed from, or, until its first claim, to its namespace's, and to the controls channel.
Every channel carries the {_shared} hash tag, so on a Redis Cluster a node sends its SUBSCRIBE and PUBLISH to the primary that holds the store's keys, as it does its scripts, rather than to whichever primary the client picks.
Notifications for SQL stores¶
UseRedisNotifications adds Redis wake-ups to a store that keeps its jobs elsewhere, such as the PostgreSQL, SQL Server or SQLite store. It uses two of the channels above, under its own KeyPrefix (bellhop: by default) and the node's namespace, and every node subscribes to both:
| Channel | Published when |
|---|---|
<prefix>{_shared}{<namespace>}:wake |
a store write made a job Enqueued: a job created, promoted, handed back at shutdown, requeued, returned from Unroutable or taken back from an expired lease, or a continuation, batch continuation or recurring occurrence the write released or started |
<prefix>{_shared}:controls |
a queue resumed, a queue's concurrency limit changed, the maintenance pause turned off, or a concurrency key's Max or a rate limit changed |
The message is 1, and receivers ignore what it holds: a message only makes a node claim from its store at once rather than at its next poll, and the claim reads the store as a poll does. A job created in the application's own transaction publishes nothing, as Bellhop does not see the commit, so the next poll finds it; nor does a run that ends while holding a concurrency key or a slot of a queue's limit, as the PostgreSQL store's NOTIFY does not either. Queue channels are not used: a node does not know the queues of every job a write moved.
On Redis the mode sends only PUBLISH, SUBSCRIBE and UNSUBSCRIBE, besides StackExchange.Redis's own commands when it connects: no TIME, no script, and no key is ever read or written. A multiplexer Bellhop opens from a connection string has no tie-breaker key, so its connect sends no GET either; a multiplexer the application gives is used as the application configured it. Pub/sub belongs to no database, so the connection string's defaultDatabase does not matter.
The channels are the Redis store's, so an installation that keeps its jobs in Redis under the same prefix can wake the nodes of this mode, and they its nodes, each such wake costing one claim that finds nothing. The controls channel carries both ways, whatever the namespaces. On the wake channel of a shared namespace, every enqueue of the Redis store wakes this mode's nodes, but this mode's signals reach a Redis-store node only until its first claim, after which it listens on its queues' channels instead. A distinct KeyPrefix keeps them apart.
Commands¶
The store sends no command outside this list, directly or inside its scripts, and only on database 0. The list is the ceiling its tests enforce, not what it sends today: it sends no RPOP, LMOVE, BLMOVE, SCRIPT LOAD, MULTI or EXEC (below); "An ACL user for the store" lists the commands it does send.
| Kind | Commands |
|---|---|
| Strings | SET with NX and PX only, GET, DEL, INCR, DECR, EXPIRE, PTTL |
| Hashes | HSET, HGET, HMGET, HGETALL, HINCRBY, HDEL, and EXPIRE of a whole hash |
| Lists | LPUSH, RPUSH, RPOP, LMOVE, BLMOVE, LREM, LRANGE, LLEN |
| Sorted sets | ZADD, ZREM, ZSCORE, ZCARD, ZRANGEBYSCORE with LIMIT (without it only in expire-api-keys, under "Short" above), ZRANGE by rank, and with BYSCORE, REV and LIMIT, ZREMRANGEBYSCORE, ZPOPMIN, ZRANK |
| Sets | SADD, SREM, SMEMBERS, SISMEMBER |
| Pub/sub | PUBLISH, SUBSCRIBE, UNSUBSCRIBE |
| Scripts and transactions | EVAL, EVALSHA, SCRIPT LOAD, MULTI and EXEC with no EVAL or EVALSHA between them |
| Server | TIME, once per store call; HELLO, INFO, EVAL "return 1" 0 and CONFIG GET, for checking the server (below) |
StackExchange.Redis also sends commands of its own when it connects, to keep the connection alive, to discover the topology and to follow a Cluster's redirects: AUTH, HELLO, CLIENT SETNAME, CLIENT SETINFO, CLIENT ID, PING, ECHO, INFO, CONFIG GET, CLUSTER NODES, CLUSTER SLOTS, CLUSTER SHARDS, ASKING before a command it sends again to the server an ASK redirect names, READONLY to a Cluster's replicas, SENTINEL, ROLE, SUBSCRIBE to its own configuration channel and UNSUBSCRIBE, GET of its tie-breaker key, and QUIT. Of these, the store's own code sends only TIME, HELLO with no argument, INFO and CONFIG GET as below, and UNSUBSCRIBE of its wake channels: of the namespace's once a claim's queues are subscribed, of a channel whose SUBSCRIBE failed, and of every one at dispose.
The store checks the server on every connection before its first call on it, and again after a lost connection or a change of roles; on a Cluster, the server it checks is the primary that owns the slot of _shared, where its scripts run: the server the client routes the slot to, once a CLUSTER NODES reply the client holds names it the slot's primary, since the client routes a slot whose owner it cannot reach to another primary; until then the store is in an outage and checks no other server. A slot that moves to another server is a new connection. The check: HELLO with no argument and INFO with no argument identify the family and version and read the persistence, eviction policy and replicas, and the trivial script return 1, sent as EVAL and never EVALSHA, probes scripting. CONFIG GET maxmemory-policy and CONFIG GET appendonly follow only when INFO lacks maxmemory_policy or aof_enabled. When the HELLO shows the connection an earlier check already ran on, unchanged (the same server, connection id, role and client socket), nothing else follows: the client can report one reconnection several times. A server that answers HELLO or INFO as a replica stops the check, as an outage. Each health-check run sends one INFO, and CONFIG GET appendonly when INFO lacks aof_enabled. StackExchange.Redis sends INFO and CONFIG only with allowAdmin, which the store sets on the multiplexer it opens; on a multiplexer the application gives it without allowAdmin, the store sends INFO as EVAL "return redis.call('INFO')" 0 and no CONFIG GET.
The store sends no MULTI: StackExchange.Redis sends SELECT with every transaction, so reads that must agree are made in one script or checked by the script that acts on them.
The store never uses modules, FUNCTION or FCALL, Streams, keyspace notifications, hash-field expiry (HEXPIRE and its family), CLIENT TRACKING, KEYS, ZRANGEBYLEX, SELECT, WAIT, MSET, or any command only Redis 8 has, so it runs on Redis 7.2, Valkey and other Redis-compatible servers with no module loaded.
An ACL user for the store¶
The store can connect as an ACL user other than default (the user= and password= of its connection string). The user needs the keys and channels under the store's prefix, the commands the store and its scripts send, and the few StackExchange.Redis sends to connect; nothing else. Its key and channel patterns end with {_shared}, the tag every key and channel of a store carries right after the prefix, so that a grant for one prefix never matches the keys of another prefix that starts with it (app and apple:); a prefix holding *, ?, [, ] or \ needs those escaped with \ in the pattern. For the prefix bellhop:, create it on every server of a standalone setup:
ACL SETUSER bellhop reset on >password ~bellhop:{_shared}* &bellhop:{_shared}* +get +set +del +incr +decr +expire +pttl +hset +hget +hmget +hgetall +hincrby +hdel +lpush +rpush +lrem +lrange +llen +zadd +zrem +zscore +zcard +zrange +zrangebyscore +zremrangebyscore +zpopmin +zrank +sadd +srem +smembers +sismember +publish +subscribe +unsubscribe +eval +evalsha +time +hello +info +echo +ping +client|setname
On the primary and every replica of a Sentinel set, the same with ROLE, which StackExchange.Redis asks a server it reached through the Sentinel:
ACL SETUSER bellhop reset on >password ~bellhop:{_shared}* &bellhop:{_shared}* +get +set +del +incr +decr +expire +pttl +hset +hget +hmget +hgetall +hincrby +hdel +lpush +rpush +lrem +lrange +llen +zadd +zrem +zscore +zcard +zrange +zrangebyscore +zremrangebyscore +zpopmin +zrank +sadd +srem +smembers +sismember +publish +subscribe +unsubscribe +eval +evalsha +time +hello +info +echo +ping +client|setname +role
and on every Sentinel, which the client asks for the primary and listens to for a new one (+switch-master) and for other Sentinels (+sentinel), with the same password, as the client connects to the Sentinels with the user and password of its connection string:
ACL SETUSER bellhop reset on >password &+switch-master &+sentinel +sentinel|get-master-addr-by-name +sentinel|masters +sentinel|replicas +subscribe +ping +info
On every server of a Cluster (ACL users are not shared between a Cluster's servers), the same as standalone with CLUSTER NODES, which the client reads the slot map with, and ASKING, which it sends before a command it sends again to the server an ASK redirect names while a slot moves: every key of a store is in one slot, so while a resharding moves that slot, a user without ASKING is refused every call on a key already moved.
ACL SETUSER bellhop reset on >password ~bellhop:{_shared}* &bellhop:{_shared}* +get +set +del +incr +decr +expire +pttl +hset +hget +hmget +hgetall +hincrby +hdel +lpush +rpush +lrem +lrange +llen +zadd +zrem +zscore +zcard +zrange +zrangebyscore +zremrangebyscore +zpopmin +zrank +sadd +srem +smembers +sismember +publish +subscribe +unsubscribe +eval +evalsha +time +hello +info +echo +ping +client|setname +cluster|nodes +asking
The list is what the store sends today, narrower than the baseline above: no RPOP, LMOVE, BLMOVE, MULTI, EXEC or SCRIPT LOAD. A script's commands are checked against the user too, so its data commands are on the list though the store sends them only inside EVALSHA. ECHO is required: StackExchange.Redis refuses a connection whose ECHO fails. CLIENT SETNAME gives the connection the name= of the connection string; without it the store runs, but its connections are unnamed in CLIENT LIST and MONITOR.
StackExchange.Redis also sends commands the store does not need, which the user above is refused, with no effect on the store: CLIENT SETINFO and CLIENT ID; CONFIG GET; CLUSTER SLOTS, and CLUSTER NODES off a Cluster; READONLY to a Cluster's replicas, which the store never reads from; GET of its tie-breaker key __Booksleeve_TieBreak, which only picks between primaries a connection string names side by side; and SUBSCRIBE to its own __Booksleeve_MasterChanged, a broadcast of role changes made with the client's own primary-switching call, which the store never makes. A server records each refusal in ACL LOG. CONFIG GET is left out on purpose: the store reads the eviction policy and the persistence from INFO, and CONFIG GET would let the user read every setting, requirepass and masterauth among them. Grant +config|get only on a server whose INFO lacks maxmemory_policy or aof_enabled, where the store needs it to check those.
The migration lock¶
A node migrates the layout while it holds <prefix>{_shared}:migration-lock, which it sets to a token of its own with SET NX PX 30000. While another node holds the lock, the node logs LayoutMigrationLockWaiting (event 4300) once and tries again every 200 ms; once it has the lock, it reads the stored version again and applies only what is still missing. Each migration's script records its version only while the lock still holds the node's token, so a node that held the lock past its expiry writes nothing, and its start fails; the next start migrates. The node releases the lock with a script that deletes it only while it holds the node's token, also when its migration failed or was cancelled; when the release itself fails, the node logs LayoutMigrationLockNotReleased (event 4301) and the lock expires on its own. A node that dies holding the lock leaves it for at most 30 seconds.
Migrating by hand¶
With Bellhop:AutoMigrate off, an operator records each layout version from the stored one up to the expected one, in order, while no node is migrating. Replace bellhop: with the store's prefix; a store with no layout field is at version 0.
| Version | What it changes | Command |
|---|---|---|
| 1 | records layout version 1; its keys are created as they are first written | HSET bellhop:{_shared}:store layout 1 |
For example, on the default prefix: