SHADE is young: 0.1.0-next.2 is a pre-release, and 0.1.0 isn't out yet.

SHADE
Developers

Redis and the ports

Every instance has a Redis beside Postgres. Postgres holds the records: anything that must survive, be backed up, exported or erased. Redis holds only work in flight, which can be rebuilt: leases, the queue's jobs, messages between containers, rate-limit counters and the cache. The API refuses to start without it.

"Redis" here is the role, not one product: any server that speaks the Redis protocol works. SHADE's compose files and deployment template ship Valkey (valkey/valkey:9.1-alpine), which is BSD-licensed. Redis 8 is licensed AGPLv3, RSALv2 or SSPL, and SHADE promises clients no licence questions (Rejected alternatives).

Code never talks to Redis itself. The kernel declares five ports, the API's driver implements them on Redis, and everything else uses the ports on the service context. Tests use the same ports in memory.

Where it is

PartWhat
shade/kernel/ports.tsThe ports: Leases and Lease, WorkQueue and QueuedJob, Messages (ShadeChannel, ShadeMessage), Counters, Cache; CoordinationPorts is all five.
shade/kernel/context.tsServiceContext has them as optional leases, queue, messages, counters and cache.
shade/kernel/coordination/leases.tsWhat a lease is, written once for both implementations: leasesOn(store, clock) on a store's atomic steps (take, extend, drop, and claim for once).
shade/kernel/coordination/memory.tsmemoryCoordination(clock?): the five ports in memory, the same rules as Redis, with a clock a test drives (manualClock()).
shade/kernel/coordination/contract.tscoordinationContract(name, make): the one test suite both implementations pass.
shade/kernel/coordination/follow.tsMessages replacing polling: announce(ctx, channel, kind) after a change commits, follow({ messages, channels, reread }) in each container, SAFETY_REREAD_MS (60 s).
apps/api/src/redis/driver.tscreateRedisPorts(url): the five ports on ioredis, one client plus one connection for subscriptions.
apps/api/src/redis/scripts.tsThe Lua scripts, each atomic on Redis: RELEASE, RENEW, HIT, and the queue's PROMOTE and SETTLE.
apps/api/src/bootstrap/runtime.tsruntime.redis, made on first use; close() closes both connections.
apps/api/src/http/context.tsEvery request's context gets the five ports (made on first use, like storage).
apps/api/src/bootstrap/start.tscheckRedis: start-up pings Redis and stops with what to check when it does not answer; then runtime.follow().
apps/api/src/bootstrap/restart.tsfollowRestartRequests: the restart channel, used by server.ts.

ioredis is imported only in apps/api/src/redis/. pnpm lint refuses it anywhere else, core, modules, sites, scripts and tests included (eslint.config.mjs; held by test/scripts/redis-imports.test.ts).

The messages port is used: messages replace the polling for the module switch, roles, the sandbox, the Site URL and restarts (below). The leases port is used by the worker container role's Scheduler (each due time once, a lease per run) and by the rebuild, and the cache by the worker's heartbeat (The worker container role). The counters hold every rate limit (below). The other users move onto the ports in their own pull requests; the queue port carries core's queued jobs on the worker (below). kv uses none of them: modules' keys and counters are in Postgres (kv). Modules will reach them only through the providers' SDK wrappers, under package:<name>:, never raw.

The ports

Leases (one holder at a time: schedules, singleton processes, the rebuild).

  • acquire(name, ttlMs, holder) takes the lease when nobody holds it: SET shade:lease:<name> <holder>:<token> NX PX. The token comes from shade:lease:<name>:token: one above the last, and never below Redis's clock in microseconds (the Lua script NEXT_TOKEN), so it grows with every new holder, also after Redis restarted and kept nothing (fencing: a write that must not race a takeover compares it). It is a whole number of about 16 digits: store it as a bigint. Returns the Lease, or null.
  • lease.renew(ttlMs?) extends it only while this holder still holds it (Lua compare-and-extend). False, and lease.lost aborts, when it was lost, or when Redis does not answer: the holder stops rather than run on while another may take over.
  • lease.release() gives it up only while still held by this holder (Lua compare-and-delete), and aborts lost.
  • hold(name, ttlMs, holder, signal) acquires and renews every third of the TTL until signal aborts (then it releases) or a renewal fails.
  • resume(name, ttlMs, holder, token, signal) holds again, as hold does, a lease its holder lost to a renewal Redis did not answer, while the key still holds <holder>:<token> (the same compare-and-extend). A key taken over or run out meanwhile is left alone: null. The rebuild lease uses it, so one blip doesn't hand the rebuild to another worker.
  • holderOf(name) says who holds it and until when.
  • once(name, ttlMs, holder) marks something done once: SET shade:once:<name> <holder> NX PX, true for the first holder only until it expires, with no token and no renewal. The Scheduler takes each schedule's due time with it (once:schedule:<schedule>:<due time>), so one worker runs each due time.

With two workers or more, each has a rebuild trigger of its own that debounces in its memory, while the entries' event deliveries are shared out between them. Left alone, ten pages published in a minute could start a build on each worker. So the worker that holds the lease rebuild:content-delivery is the only one that claims the deliveries asking for a rebuild (the rebuild's own and the path moves'), and its trigger builds the whole burst once. A worker gives the lease back as it shuts down, so on a restart or a rolling update the next one claims at its next poll. One that stops answering loses it up to 30 seconds after its last renewal, and another worker takes it then. Changes made in the admin (site settings, media, a module switched on or off, a publish of many entries at once) still ask the admin container's trigger.

Queue (jobs in flight; the outbox, and what a job that ran out of tries leaves behind, are in Postgres: see Core's queues). A Redis stream per queue (shade:queue:<queue>) with the consumer group shade.

  • add(queue, payload, { delayMs?, dedupeKey? }): now on the stream, or later from a sorted set by due time. A dedupe key gives one job per key until it is acked; it lasts a day after the job was added, retried or postponed, so it holds for as long as the job is in flight. A job starts at attempt: 1.
  • claim(queue, consumer, { max, visibilityMs }) moves due delayed jobs onto the stream, takes back jobs claimed longer than visibilityMs ago and never acked (XAUTOCLAIM), then reads new ones (XREADGROUP). A job taken back counts as a try: its attempt goes up by the times it was handed out (XPENDING's delivery count).
  • ack(queue, id) removes it; retry(queue, job, delayMs) puts it back later with attempt + 1; postpone puts it back with the same attempt (an open breaker); depth(queue) counts ready, delayed and claimed jobs.
  • After a Redis restart the stream and its group are gone: the driver makes the group again when Redis answers NOGROUP, so the worker goes on without a restart of its own.

Messages (between containers). publish(channel, { kind, version? }) and subscribe(channel, handler, onReconnect?) on Redis pub/sub (shade:msg:<channel>). A message says "re-read", never the truth: anything but kind and version is dropped, so a forged one can at most cause a re-read. After a lost connection the driver subscribes again, then calls each onReconnect, so its subscriber re-reads what it may have missed.

Counters (rate limits). hit(key, { limit, windowMs }) counts one attempt atomically in a fixed window (Lua: INCR, then PEXPIRE on the first hit), so a burst at once never passes the limit. peek(key) reads a count without counting (0 once its window ended), reset(key) starts it again.

Cache. get, set(key, value, ttlMs, { group? }) (the TTL is required: nothing in Redis lives forever), delete(key, { group? }), and take(key), which returns and deletes in one step (GETDEL), for single-use values such as approval tickets. A group ({ name, limit }) keeps at most limit values together, dropping the oldest written (shade:cache-group:<name>, a sorted set by write time, one script CACHE_SET on Redis): the modules' cache keeps each module's values in one (Background work and services).

Keys: shade:lease:…, shade:once:…, shade:queue:…, shade:counter:…, shade:cache:…, channels shade:msg:… (shade: is REDIS_PREFIX: an instance keeps it; the browser tests' servers, which share one Redis, set one each). Values go through JSON, in memory too. Only a lease's fencing token and a queue's stream have no expiry (a token must only grow); after Redis loses its data a token starts again from Redis's clock, which is past every token given before.

Counters

Every rate limit counts here, so the containers of an instance share each budget: sign-in and the team's auth steps, the account API's limits (account.auth.*, account.*, account.data), error reports, modules' webhooks, MCP, modules' route limits, the approval step's re-authentication and the sandbox's call limit for untrusted modules. See Request protection (shade/kernel/protection/README.md in the shade repository) for each limit.

  • Windows. hitRateLimit (shade/kernel/protection/protection.ts) keeps a sliding window: windows aligned to the clock, each its own counter (shade:counter:<limit>:<client>:<window>) that lives two windows; a request hits this window's and peeks the previous one's, weighted by how much of it still lies in the last window. Retry-After and RateLimit-Reset are the seconds until this window ends. The sandbox's call limit is a plain fixed window from the module's first call (shade:counter:sandbox.calls:<plugin>).
  • Keys without addresses. The client in a key is an HMAC of the address (IPv4 as it is, IPv6 by its /64), token, account or user, with APP_SECRET.
  • Fails closed. While Redis does not answer, a limited request is refused with 503 (UNAVAILABLE, Retry-After: 5), never let through uncounted, and the first 503 of every five seconds is in the error log. Once the connection is known to be down the driver fails a count at once instead of waiting for reconnection attempts. Sign-in, the account API, modules' limited routes and the sandbox's calls stop until Redis is back; reading content and the admin's other routes go on.
  • A restart starts the counts again. Counters are not records: Redis losing them resets every budget, and the per-account limits and the audit of refusals still hold for the next attempts.

Messages replacing polling

Each container keeps some things from Postgres in memory: which modules are on, the custom roles, the untrusted modules in its sandbox, the Site URL with the frontends' and framed origins. The container that changes one tells the others, and they re-read it at once.

  • Postgres stays the truth. A message only says "re-read" ({ kind }); the container reads the change from Postgres. A forged message can at most cause a re-read, and a restart only happens for a row in instance_restarts newer than the process.
  • Announced after commit, never waited for. A service calls announce(ctx, channel, kind) once its transaction committed. It does not wait for Redis and never throws: the change is saved, so a message that cannot be sent (Redis away) never fails or slows the request. Without the messages port (scripts, most tests) it does nothing.
  • Followed with a safety net. follow({ messages, channels, reread }) subscribes, and re-reads:
    • at once on a message on one of its channels;
    • at once when the connection to Redis comes back (onReconnect), for what it may have missed;
    • every 60 seconds (SAFETY_REREAD_MS), in case a message was lost: a lost message delays a change by a minute at most;
    • once just after subscribing, for what changed between start-up's read and the subscription.

    Re-reads never run twice at once: what comes in during one makes one more afterwards.
  • Untrusted modules within 5 seconds. A sandbox stop or switch must not wait a minute for a lost message, so every container also compares the untrusted modules' switch and versions with Postgres every 5 seconds (UNTRUSTED_SWITCH_REREAD_MS in runtime.ts), in one small query (untrustedSwitchState: each untrusted module, its version time and its switch), and reloads its sandbox only when that changed. Everything else keeps the 60 seconds. A failed re-read is logged once and tried again at the next message or tick; a failed subscription is tried again at the next tick.
ChannelAnnounced byEach container then
pluginsa switch on or off (switchInstalledModule, so also the watchdog stopping an untrusted module), a removed server package, an optional capability switchedreloads the switch and its sandbox (runtime.reloadUntrustedModules), and forgets the framed origins
sandboxan untrusted module installed, updated or removedreloads the untrusted modules and its sandbox
rolesa custom role created, changed or deletedreloads the custom roles (loadCustomRoles)
sitea changed Site URL or time zone, a frontend added, changed or removed, a module's settings saved (they may hold a framed address, such as the website module's Preview address)forgets the Site URL, the time zone (which modules' cron schedules without their own run in), the frontends' origins and the framed origins; the next use reads them again
restartan admin's restart request (requestRestart)checks latestRestartRequest, and stops gracefully when it is newer than the process

The API's runtime follows the first four (Runtime.follow(), called by start-up once the modules are loaded and stopped by close()); server.ts follows restart (followRestartRequests). The queue channel wakes the worker's relay (below), and a realtime:<plugin>:<topic> channel carries a module's realtime updates to the streams open on that topic in every container (Realtime).

Core's queues

Built for core's own work; outgoing webhooks are the first user. A job may wait until a time and carry a key, email's retries and planned notifications are jobs, and trusted modules have jobs of their own (below).

  • shade/kernel/queue/queue.ts (the kernel's, beside the consumer): defineQueue({ name, concurrency, retries, backoffMs, timeoutMs, handle, giveUp }), at import by the part that owns the queue (webhooks.deliver in features/webhooks/server/webhooks.ts). enqueue(tx, queue, data, { runAt, key }) writes a job into queue_outbox in the transaction of the change that asks for it, so a job exists exactly when its change committed. With runAt it waits there until then (Redis holds only what is due); with key it replaces the job waiting under that key in its queue (a partial unique index), and cancelJob(tx, queue, key) takes it back. A job already sent that was replaced or taken back is skipped at its next try (each try first checks that its row still waits); a try running at that moment still ends. announceJobs(ctx) after the commit wakes the worker (the queue channel): by hand after the transaction, or as an afterCommit step of an inTransaction (emitEvent, kernel/context.ts). Announced before the commit, the relay would not see the job yet and it would wait for the next poll.
  • relayOutbox(db, queue) marks the outbox's jobs that are due sent, reading their data in the same step (FOR UPDATE SKIP LOCKED, so two workers never take one job and a job replaced meanwhile gets a row of its own), then adds them to the queue under their outbox id (the dedupe key, so a job sent twice runs once while it is in flight). One sent but not done after OUTBOX_RESEND_MS (an hour) is added again in case Redis lost it, and at once when the queue no longer holds the dedupe key of its oldest job in flight (WorkQueue.holds): Redis restarted and kept nothing. One still in flight holds its dedupe key, so neither adds a second copy. Only the jobs of queues defined on the worker are sent: a module's jobs that never finished go when it is uninstalled. settleJob marks a job finished (finished_at, outcome done or gave-up, attempts, the last error) and clears its data; finished jobs are purged after the retention kind queue-jobs (7 days by default, registered by the operations module, features/queue/server/kept-data.ts). Core's queues: webhooks.deliver, email.send (a failed email, five more tries) and notify.send (a planned notification, with its time and key).
  • shade/kernel/queue/consumer.ts: the kernel's QueueConsumer claims each queue's jobs (concurrency at once in a process, every QUEUE_POLL_MS (5 s), at once on wake, and when a retry comes due), gives each try timeoutMs (its signal aborts then), acks a job that went well, puts a failed one back after backoffMs × 2^(attempt − 1), at most an hour, plus up to 20 % jitter (retryDelay, on the kernel's backoffDelay), and past retries calls the queue's giveUp and acks it. A job is acked only after settleJob recorded how it ended; one whose record failed (Postgres away) stays claimed and comes back as its next try. A claimed job never acked (its worker died) comes back after QUEUE_VISIBILITY_MS (a minute), counted as a try: handlers are idempotent, and a job claimed again past its last try (it stopped the worker each time) is given up without running.
  • On the worker container role, startQueues in apps/api/src/bootstrap/worker.ts runs the relay (on the queue channel, after Redis comes back, and every OUTBOX_RELAY_EVERY_MS, 5 s) and the consumer, as the system; stopping waits for the jobs under way until the stop deadline less five seconds (SHADE_STOP_GRACE_MS), then aborts their signal and gives them back to their queue at once (the port's release), the try not counted. QUEUE_RETRY_WAIT_MS replaces every queue's first wait; only the tests change it (e2e/server.ts: 200 ms).
  • A job that runs out of tries shows where it belongs, never in a list of its own: a webhook delivery as failed on the Webhooks screen, sent again from there, and counted on its module's health card.

Modules' jobs

A trusted module declares its kinds of job (kernel/queue/module-jobs.ts; the manifest part in features/queue/server/manifest.ts) in the manifest part jobs ({ name, run(ctx, data, job), giveUp? }), each with its parameters in the queue capability (retries, backoffMs, concurrency, optional timeoutMs up to 55 s, default 30 s). enqueueJob(ctx, name, data, { runAt, key }) from the module's own context writes one in its change's transaction (and wakes the relay after the commit); cancelModuleJob(ctx, name, key) takes one back. Each kind is a queue named package:<plugin>:<job>, registered when the catalog loads. A job runs as the module's own actor (asModule), waits its tries out while the module is off, and one that gave up is in the error log (package:<name>, scope queue: <queue>) and counted on the module's health card for 7 days (failedJobsOf).

Configuration

  • REDIS_URL (required): redis:// or rediss://, with the password Redis is started with (redis://:<password>@redis:6379, a database number after the last / if wanted). Missing, without a password or of another kind, the API stops with [config] REDIS_URL: …; when Redis does not answer within 10 seconds, with Cannot reach Redis at redis://:***@…: … Check REDIS_URL and its password; in development … docker compose up -d redis. The password never reaches the log.
  • /health reports checks.redis as up or down (a ping within a second; down at once while the connection is away). /health is the readiness answer and is 503 then, so a proxy stops sending requests to the container; the process lives, and /health/live still answers 200, since restarting it would not bring Redis back.
  • The settings, the same in docker-compose.yml and deploy/compose.yml (valkey-server; valkey-cli for the health checks): --requirepass, --maxmemory 64mb, --maxmemory-policy noeviction (a full Redis refuses writes instead of evicting a lease, which would let a schedule run twice), --appendonly no --save "" (nothing it holds needs to survive). In the template it has no published port, runs as the image's valkey user with a read-only filesystem and every capability dropped, and the API containers start once it is healthy.
  • The client opens its connection with the first command (start-up's ping), retries a command at most three times while reconnecting (so a renewal fails instead of hanging) and reconnects on its own; connection errors are logged, the same one at most once a minute.

Development

pnpm dev starts the redis service of docker-compose.yml with Postgres (127.0.0.1:6379, password shade). Put REDIS_URL=redis://:shade@localhost:6379 in .env (.env.example has it). That password is for development only: an instance gets its own (REDIS_PASSWORD, generated on the first start by the deployment template, see Setting up an instance). On its own: docker compose up -d redis.

Tests

  • The contract (shade/kernel/coordination/contract.ts) runs on the memory ports (shade/test/kernel/coordination/leases.test.ts, unit, with the test clock) and on Redis (apps/api/test/redis/driver.test.ts, in the db project). Leases: "gives a lease to one holder at a time", "lets another holder take over after the lease expires", "renews and releases only for the holder", "raises the fencing token on every new holder", "aborts lost when a renewal fails", "marks a due time once across holders, until it expires". The queue: one consumer per job, at most max oldest first, taken back after the visibility time, delayed and retried with the attempt raised, one job per dedupe key. Messages: every subscriber of a channel and no one after unsubscribing, "carries only kind and version: a message says re-read, never the truth", onReconnect after a lost connection (on Redis the test cuts the subscription's connection with CLIENT KILL). Counters: a burst of 20 counted once each, five allowed; reset. Cache: the TTL, required; single use; a group's limit, the oldest written dropped.
  • The driver (driver.test.ts): its keys and messages stay under its prefix and expire; the health check and start-up's check; a wrong password refused without showing it.
  • Messages replacing polling:
    • shade/test/kernel/coordination/follow.test.ts (memory ports, test clock): "re-reads at once when another container announces a change", "catches a lost message with the safety re-read after 60 seconds", "re-reads at once after a reconnect, for the messages it may have missed", "never re-reads twice at once: what comes in meanwhile makes one more run", "tries a failed subscription again at the safety re-read"; announcing never fails or waits.
    • apps/api/test/bootstrap/restart.test.ts: a request restarts at once and only once, a forged message changes nothing, a lost one is caught within 60 seconds, a reconnect checks at once.
    • apps/api/test/bootstrap/runtime.messages.test.ts (db project): two runtimes on one test database and the test Redis, as two containers. "gives another container a new Site URL at once", a new frontend's origin, "gives another container a new custom role at once", "switches a module in another container at once", "restarts another container at once when an admin asks", "re-reads at once when Redis comes back, for what it missed meanwhile" (the test cuts the subscription's connection); and on the memory ports with a test clock, "catches a change whose message was lost, within 60 seconds" and "catches a lost message about an untrusted module's stop within 5 seconds, while the rest waits for 60".
    • The browser tests run every API on the test Redis, so switching modules, roles and settings there goes through the messages too.
  • Configuration and start-up: apps/api/test/config.test.ts ("refuses to start without REDIS_URL", and an address without a password), apps/api/test/bootstrap/start.test.ts (no Redis at the address), routes/web.test.ts (/health with Redis down) and e2e/tests/health.spec.ts (up, on the test Redis).
  • Deployment: test/scripts/deploy-template.test.ts holds the Redis service's settings and REDIS_URL on the three API container roles; pnpm deploy:smoke checks in the running template that they reach Redis, that it asks for its password and that its policy is noeviction.
  • The test Redis: the redis-test container of docker-compose.yml (Valkey, 127.0.0.1:6380, nothing on disk), started by the tests themselves (scripts/test-redis.mjs), or SHADE_TEST_REDIS_URL. Test slot n uses its database n; each driver test case keeps its keys under a prefix of its own and removes them. The browser tests' APIs and the site's run on it too (E2E_REDIS_URL points them elsewhere).