Operating Apiome
This page is the starting point for the people who run an Apiome installation rather than use it: how the services fit together, where each one is configured, and the runbooks for deploying, backing up and triaging. The admin console, the screen operators use day to day, has its own pages in this group.
The stack
docker compose up from the repository root runs the back end; the web app (apiome-ui) runs
beside it (yarn dev in development, its own image in production).
| Service | What it is | Host port (default) |
|---|---|---|
postgres | The database every service shares | 5432 (POSTGRES_PUBLISH_PORT) |
migrate | Applies the apiome-db migrations, then exits | — |
seed | Loads the development seed data, then exits (never in production) | — |
rest | apiome-rest, the REST API | 8000 (APIOME_REST_HTTP_PORT) |
mcp | apiome-mcp, the MCP server | 8765 (APIOME_MCP_HTTP_PORT) |
mock | apiome-mock, the mock runtime | 8775 (APIOME_MOCK_HTTP_PORT) |
minio | S3-compatible object storage for the document store; used only when APIOME_DOCUMENT_STORE=s3 (never in production) | 9000, console 9001 (MINIO_API_PUBLISH_PORT, MINIO_CONSOLE_PUBLISH_PORT) |
minio-init | Creates the document-store bucket in MinIO, then exits (never in production) | — |
redpanda | Optional single-node Kafka broker for AsyncAPI mocks; only with --profile broker | 19092 (APIOME_DEV_BROKER_HOST_PORT) |
Production applies
docker-compose.prod.yml on
top of docker-compose.yml: it adds
caddy (TLS from Let's Encrypt, the only service with host ports — 80 and 443), backup
(encrypted scheduled backups) and the Studio image, and keeps seed out of up. The Studio image
builds from private-suite/designer/Dockerfile with the private-suite repository checked out
beside apiome-ui in the same tree, so docker compose build leaves the web app and Studio on the
same sign-in code; rebuild both whenever you move the checkout.
redpanda is off by default: it starts only with docker compose --profile broker up, and no
other service waits for it. rest and mock are already wired to it as redpanda:9092
(APIOME_MOCK_DEV_BROKER_BOOTSTRAP). Production doesn't use the profile. There, tenants bind their
own clusters, and APIOME_MOCK_BROKER_ALLOW_PRIVATE must stay false. See
Event mock brokers.
To try Apiome on one machine, follow Run Apiome locally.
Environment reference
Every service reads its settings from environment variables. Each workspace ships an annotated
.env.example — copy it to .env and change what you need:
| File | Configures |
|---|---|
docker-compose.env.example | The Compose stack: database credentials, host ports, shared tokens |
docker-compose.prod.env.example | Production: domains, TLS, backup key, fail-closed secrets |
apiome-ui/.env.example | The web app: database, auth secret, sign-in providers, the admin console password |
apiome-rest/.env.example | The REST API |
apiome-mcp/.env.example | The MCP server |
apiome-mock/.env.example | The mock runtime |
apiome-db/.env.example | Migrations |
apiome-cli/.env.example | The command-line client |
The admin console's own settings — ADMIN_PASSWORD and ADMIN_SESSION_SECRET — are described on
The admin console.
Database connections
The REST API gives each worker thread its own database connection, so concurrent requests run
their queries side by side. When a worker thread ends, its connection goes back to a pool for the
next thread. DB_POOL_MAX_IDLE (default 10) sets how many idle connections the pool keeps; the
rest are closed.
Each background job (webhook delivery, repository refresh, usage roll-up and the others) keeps one handle for as long as the API runs. Its connection goes back to the pool between runs, so a job does not reconnect every time it runs.
DB_POOL_MAX_IN_USE (default 80) caps the connections one API instance can have in use at once,
counting worker threads and background jobs together. A request that needs a connection past the
cap fails at once with 503 and error type database_busy, instead of opening another connection.
The log line names the setting.
To size it, keep this sum below PostgreSQL's max_connections, minus what other clients and
superuser sessions need:
DB_POOL_MAX_IN_USE × REST API instances + DB_POOL_MAX × web app instances + DB_POOL_MAX ×
browse site instances
With the defaults, two API instances and one of each app need 80 × 2 + 10 + 10 = 180 connections,
which is more than PostgreSQL's default of 100. Raise max_connections or lower
DB_POOL_MAX_IN_USE.
Add the MCP server too: each apiome-mcp instance serving HTTP keeps two pools, up to
APIOME_MCP_DATABASE_POOL_MAX_SIZE + APIOME_MCP_AGENT_DATABASE_POOL_MAX_SIZE connections
(10 + 10 by default). See
The MCP server's database work per call.
The mock runtime keeps one pool of up to APIOME_MOCK_DATABASE_POOL_MAX_SIZE connections
(default 10) per instance. Add it too. See
The mock runtime's database work per request.
The web app keeps its own pool of up to DB_POOL_MAX connections (default 10). The public
browse site keeps a pool of its own, sized by the DB_POOL_MAX set on the browse service (default
10 as well). The two are separate settings on separate services, so you can size them apart. Add
both to the total. The web app's Home page uses at most three of its connections at once, so
other people's pages keep loading while it does.
Request threads
The REST API runs the database work of each request on a worker thread, not on the thread that
accepts connections. One slow query or lock wait holds only its own thread: other
requests keep being answered, and so do the /livez, /readyz and /health probes.
REQUEST_THREAD_POOL_SIZE (default 40) sets how many requests can be at work at once in one
API instance. A request that arrives while all of them are busy waits for a free thread. Each
working thread holds one database connection, so the API never uses more than half of
DB_POOL_MAX_IN_USE for request threads. The other half stays free for background jobs, imports
and exports. With the defaults, 40 threads fit the cap of 80 exactly.
If you set REQUEST_THREAD_POOL_SIZE above half of DB_POOL_MAX_IN_USE, the API lowers it and
logs a warning at startup that names both settings. To serve more requests at once, raise
DB_POOL_MAX_IN_USE first, then check the sum above against max_connections.
The startup log shows the size in use:
request thread pool: 40 worker threads (DB_POOL_MAX_IN_USE=80)
Limits on a stuck session
A statement waiting on a lock that never clears, or a transaction left open, would otherwise hold its connection for good and stall everything behind it. The REST API, the web app and the browse site set limits on every connection they open, so a stuck session ends with an error instead:
| Setting | Service | Default | What it limits |
|---|---|---|---|
DB_LOCK_TIMEOUT_MS | REST API, web app | 30000 | How long a statement waits for a lock before it fails. |
DB_IDLE_IN_TRANSACTION_TIMEOUT_MS | REST API | 300000 | How long a connection may sit in an open transaction before PostgreSQL ends the session and releases its locks. |
DB_IDLE_IN_TRANSACTION_TIMEOUT_MS | Web app | 60000 | The same, for the web app's connections. |
DB_CONNECT_TIMEOUT_SECONDS | REST API | 10 | How long to wait for a new connection to PostgreSQL. |
DB_STATEMENT_TIMEOUT_MS | REST API | 30000 | How long one statement may run on a request. A statement that runs longer fails, and the request answers 503 with error type statement_timeout. |
DB_STATEMENT_TIMEOUT_MS | Web app, browse site | 30000 | The same limit for the web app's and the browse site's statements. A statement that runs longer fails, and the page section or action that ran it shows an error. On the browse site a search that runs longer shows the page This search did not finish. with a Try again button, and the search palette's suggestion request answers 503 with Retry-After. |
DB_LONG_STATEMENT_TIMEOUT_MS | REST API | 1800000 | How long one statement may run in an import, an export, a document migration or a background job. |
DB_POOL_CONNECTION_TIMEOUT_MS | Web app | 10000 | How long a request waits for a free connection when all of the pool's are in use. |
0 turns a limit off. The REST API skips its session limits when DATABASE_URL already carries
an options parameter, so yours win.
If the app stops responding, look at what the sessions are doing. Each service names its
connections (apiome-rest, apiome-ui, apiome-browse, and apiome-mcp-catalog /
apiome-mcp-agent for the MCP server's two pools):
SELECT pid, application_name, state, wait_event_type, wait_event,
now() - xact_start AS in_transaction_for,
pg_blocking_pids(pid) AS blocked_by,
left(query, 80) AS query
FROM pg_stat_activity
WHERE datname = current_database() AND state <> 'idle'
ORDER BY xact_start;
A row whose state is idle in transaction and whose pid appears in other rows' blocked_by is
the session holding everyone up; SELECT pg_terminate_backend(<pid>); ends it.
How long sign-in and permission checks are cached
To decide whether a request may run, the REST API needs to know whether the caller belongs to the workspace, is one of its administrators, and what their role allows. It finds all of that with one database query and reuses the answer:
- Within a request: every check in the same request uses the first answer.
- Across requests: each API instance keeps the answer for
AUTH_CACHE_TTL_SECONDS.
A change made through the REST API applies on the next request on the instance that made it. That
covers adding, suspending or removing a member, assigning a role, and editing a role's permissions.
A change made in the web app, or on another instance, applies once the cached answer expires, so
within AUTH_CACHE_TTL_SECONDS.
API keys work the same way. bcrypt is deliberately slow, so checking a key against its stored hash
is the costly part, and a key that passed recently skips it for API_KEY_CACHE_TTL_SECONDS. Each
request still reads the key's own row. A key that is deleted, disabled, expired or regenerated, or
whose workspace is disabled, is refused on its next request, wherever that change was made.
| Setting | Service | Default | What it does |
|---|---|---|---|
AUTH_CACHE_TTL_SECONDS | REST API | 30 | Seconds an instance reuses a user's workspace access and permissions. 0 looks them up on every request (once per request). |
API_KEY_CACHE_TTL_SECONDS | REST API | 60 | Seconds an instance skips the bcrypt check for a key that already passed it. 0 checks on every request. |
AUTH_CACHE_MAX_ENTRIES | REST API | 10000 | Most entries each of the two caches keeps; past it the oldest are dropped. |
Lower AUTH_CACHE_TTL_SECONDS if role changes made in the web app must apply sooner. Each cached
answer saves several statements on every request, so 0 costs the most.
The MCP server's database work per call
apiome-mcp serves two apps from one process: the catalog at /mcp and the agent runtime at
/agent/mcp. Each has its own connection pool, named in pg_stat_activity as
apiome-mcp-catalog and apiome-mcp-agent. Every connection runs in autocommit mode, so a read
is one round trip with no BEGIN or COMMIT.
What one call costs. Once a key has been used, a catalog tools/call runs one statement
before the tool's own query. That statement reads the key row, the workspace's MCP policy and the
called tool's policy row together. A warm agent tools/call runs one statement too, the key row,
and writes nothing while the agent waits. Its invocation row is written a moment later, together
with other calls' rows.
Keys. bcrypt is deliberately slow. The server runs it in a worker thread, so a key being
checked never holds up other requests. A key that passed recently skips bcrypt for
APIOME_MCP_KEY_CACHE_SECONDS. Each call still reads the key's own row, so a key that is revoked,
disabled or expired is refused on its next call, wherever the change was made. last_used_at is
written at most once a minute per key.
Policy. A change to a workspace's MCP policy applies on the next call. The policy is read with
the key on every call, so it is never cached (the freshness budget stays 0 seconds).
Agent toolsets. A toolset's manifest is reused for
APIOME_MCP_AGENT_TOOLSET_MANIFEST_CACHE_SECONDS. The manifest holds the enabled tools, accepted
descriptions, target and body capture, and the same time applies to its upstream credential rows.
An edit to the toolset itself, such as switching it off or changing its target, applies on the next
call, because the key's statement also reads when the toolset last changed. Enabling a tool,
accepting a description or rotating a credential applies within the cache time. Only encrypted
credential rows are cached: each call decrypts the one credential it sends.
Audit rows. Agent invocations, upstream credential uses, private-spec reads and capability
denials go through one writer per pool. Every APIOME_MCP_AUDIT_FLUSH_INTERVAL_MS it writes what
is waiting as one multi-row INSERT per table. On a graceful shutdown it writes everything still
waiting before the pool closes. The queue holds at most APIOME_MCP_AUDIT_QUEUE_MAX_ROWS rows.
When it is full, a new row is dropped and the call goes on, and the log line audit_rows_dropped
names the table and the running count. If a batch fails, its rows are retried one call at a time,
and only a row that fails again is lost, logged as audit_rows_failed.
Daily quota counts. Concurrent calls by one agent key share one count of the day's calls. A finished past day is counted from the daily rollup.
| Setting | Default | What it does |
|---|---|---|
APIOME_MCP_DATABASE_POOL_MIN_SIZE / _MAX_SIZE | 1 / 10 | Connections the catalog (/mcp) pool keeps open and may open |
APIOME_MCP_AGENT_DATABASE_POOL_MIN_SIZE / _MAX_SIZE | 1 / 10 | The same for the agent runtime (/agent/mcp) pool |
APIOME_MCP_DATABASE_STATEMENT_TIMEOUT_MS | 30000 | How long one statement may run. The usage sweep lifts it for its own work. 0 turns it off |
APIOME_MCP_DATABASE_IDLE_IN_TRANSACTION_TIMEOUT_MS | 60000 | How long a connection may sit in an open transaction before PostgreSQL ends the session. 0 turns it off |
APIOME_MCP_KEY_CACHE_SECONDS | 60 | Seconds a key that passed bcrypt skips it. 0 checks on every call |
APIOME_MCP_KEY_CACHE_MAX_ENTRIES | 10000 | Most keys one process remembers; the oldest go first |
APIOME_MCP_AGENT_TOOLSET_MANIFEST_CACHE_SECONDS | 5 | Seconds a toolset's manifest and credential rows are reused. 0 reads them on every call |
APIOME_MCP_AUDIT_FLUSH_INTERVAL_MS | 250 | Milliseconds between audit writes |
APIOME_MCP_AUDIT_QUEUE_MAX_ROWS | 10000 | Most audit rows waiting at once per pool; beyond it new rows are dropped and logged |
APIOME_MCP_AUDIT_BATCH_MAX_ROWS | 500 | Most rows in one INSERT |
The server skips its two session timeouts when APIOME_MCP_DATABASE_URL already carries an
options parameter, so yours win.
Measured on a scratch PostgreSQL 18 database with 50 concurrent callers and 1,000 calls in all, before and after these changes. Each row lists statements, pool checkouts, writes and bcrypt checks per call, then p50 and p95 latency:
| Call | Before | After |
|---|---|---|
Catalog tools/call (ping, keys hashed at bcrypt's default cost) | 7 statements, 6 checkouts, 2 writes, 2 bcrypt checks on the event loop; 15.5 s / 16.4 s | 2 statements (one is the tool's own), 2 checkouts, 0 writes, 0 bcrypt; 20 ms / 51 ms |
Agent tools/call, database steps only | 6 statements, 6 checkouts, 2 writes while the agent waits, 1 bcrypt; 840 ms / 1,305 ms | 1 statement, 1 checkout, 0 writes while the agent waits (0.003 batched writes per call), 0 bcrypt; 4 ms / 10 ms |
What the MCP catalog tools read and cache
The catalog's spec tools build a revision's OpenAPI document, and its listing tools page through every published spec. Both do a fixed amount of database work, whatever the size of the spec or of the catalog.
Spec documents. spec.get_openapi, spec.export_yaml, spec.describe_operation and
spec.describe_component read a revision in at most 12 statements. spec.list_operations reads
only paths and operations, in 4. spec.list_components reads only schemas and security schemes,
in 5. The first statement of each call checks that the caller may read the revision. The built
document is then kept in memory, so the next call for the same revision runs that one statement and
nothing else. A revision that changes in any way is rebuilt on its next call: the server never
serves a stale document.
Lists. spec.list, spec.list_my_specs and project.list read one page from an index, so
page 500 costs the same as page 1. The order is the one they always had: most recently changed
first, where a change to the revision, its project or one of its tags counts.
Tag counts. spec.list_tags counts the catalog's tags once and serves every page from memory
for APIOME_MCP_SPEC_TAG_HISTOGRAM_CACHE_SECONDS. A tag that is added or removed shows in the
counts within that time.
Search. spec.search ranks the matching specs first and reads project names and tags for the
page it returns only. spec.search_semantic reads from the vector index and returns the 200
nearest specs at most, so has_more is false on the page that reaches them. Use PostgreSQL with
pgvector 0.8 or later: an older pgvector can return a short page when unpublished specs still have
embeddings.
| Setting | Default | What it does |
|---|---|---|
APIOME_MCP_OPENAPI_DOCUMENT_CACHE_BYTES | 67108864 | Most built documents one process keeps, counted as their size as compact JSON (64 MiB). Memory use is several times that. The least recently used go first. 0 builds the document on every call |
APIOME_MCP_SPEC_TAG_HISTOGRAM_CACHE_SECONDS | 45 | Seconds spec.list_tags serves its counts from memory. 0 counts on every call |
Measured on the scale database (200,000 revisions, 45,000 of them public), before and after:
| Call | Before | After |
|---|---|---|
| Read a 300-path, 600-operation spec | 2,705 statements, 141 ms | 10 statements, 30 ms; nothing on the next call |
spec.list, page 1 and page 500 | 70 ms and 67 ms | 0.2 ms each |
project.list, page 1 | 53 ms | 0.1 ms |
spec.list_tags, each page | 83 ms | one count of 97 ms, then from memory for 45 seconds |
spec.search, 5,000 and 45,000 matches | 21 ms and 138 ms | 7 ms and 34 ms |
spec.search_semantic, 20,000 embedded specs | 45 ms | 8 ms |
What the upgrade changes in the database. Migration V428 stores each published revision's
place in the list, keeps one row per project for project.list, and replaces the vector index
with one over public specs only. Two things cost more afterwards:
- Publishing a revision writes two more index entries and its project's row.
- Saving a project's settings rewrites that project's published revisions, because they all move to the top of the list. That takes about 0.05 ms a revision, and about 2 ms for each revision that has an embedding.
Creating or editing a draft costs less than before. On a large database, read
Upgrade a large database without blocking writes
before you apply V428.
The mock runtime's database work per request
apiome-mock serves every hosted mock: REST, GraphQL, gRPC, SSE, WebSocket and Kafka. Its pool is
named apiome-mock in pg_stat_activity. Every connection runs in autocommit mode, so a read is
one round trip with no BEGIN or COMMIT. Writes that must happen together run in their own
transaction.
What one request costs. Once a version has been served, a REST, GraphQL or gRPC request to it runs no statement and takes no connection. Everything the request needs is cached in the process: whether the mock is on, the compiled spec, the API key, the tenant's limits and the month's usage. A streamed SSE or WebSocket message runs no statement either. Mocks that are already cached keep answering even when every connection in the pool is busy with slow queries.
Loading a spec. The first request for a version, or the first one after a publish, loads and compiles the spec. However many requests arrive at once, one of them loads it and the rest wait for that load, so a burst for a cold version holds one connection, not one per request. A REST load runs 12 statements whatever the size of the spec. The connection goes back to the pool before the spec is compiled, and compiling runs in a worker thread, so other requests keep being served meanwhile.
Keeping a spec. A compiled spec is checked again after APIOME_MOCK_SPEC_CACHE_TTL_SECONDS.
The check is one statement that compares the version's updated_at and content_stamp with the
ones the spec was compiled from. When nothing changed, the spec is kept for another period without
reloading it. A publish or a settings change reloads the spec on the next request. If that
notification is lost, the check picks up the change instead. Each process keeps up to
APIOME_MOCK_SPEC_CACHE_MAX_ENTRIES REST specs, and as many event, gRPC and GraphQL specs. A
compiled 500-operation spec takes about 0.5 MiB, so lower the limit on small instances.
Mock on or off, visibility and mode. These are cached per version for
APIOME_MOCK_ACCESS_CACHE_TTL_SECONDS. A publish or a change to the mock's settings clears the
version at once. Turning a mock off is picked up within the cache time: requests then get a
404 with problem type mock-disabled. A missing version is cached too, so repeated 404s do not
repeat the query.
API keys. A key that passed is reused for APIOME_MOCK_API_KEY_CACHE_TTL_SECONDS, and a key that
failed is refused without a lookup for APIOME_MOCK_API_KEY_NEGATIVE_CACHE_TTL_SECONDS. A revoked or
expired key stops opening private mocks within the first of those times. The cache holds a SHA-256
of the key, never the key. bcrypt runs in a worker thread, so a key being checked never holds up
other requests. A request's key is checked once, even when a /graphql call falls through to a
REST mock.
Usage counts. The Mock cell's sparkline and the monthly quota read mock_usage. The runtime
adds up its counts in memory and writes them every APIOME_MOCK_USAGE_FLUSH_INTERVAL_SECONDS as
one multi-row INSERT per table, however many requests it served. Kafka publish counts
(mock_event_publish_usage) go out with the same write. A graceful shutdown writes what is
waiting before the pool closes. If a write fails, its counts are kept and sent with the next one.
Only a crash loses counts, at most one interval's worth.
Unknown workspaces. A request for a workspace slug that does not exist is cached for
APIOME_MOCK_LIMITS_CACHE_TTL_SECONDS. Each client address may send
APIOME_MOCK_UNKNOWN_TENANT_RPS such requests per second, whatever slug it tries. Past that it
gets 429.
Audit rows. Sampled mock.request rows (APIOME_MOCK_AUDIT_SAMPLE_RATE) go through one writer
per process, one row at a time. Each append takes a per-workspace lock, so two writers, on one
instance or several, never link to the same previous row in the hash chain. A stored capture, its
review-queue count and its mock.capture audit row are written on one connection, in one
transaction.
Kafka producer. Each publishing round of a version runs one statement. It checks that the mock
is still on and reads the broker binding's state, without the credential. The adapter is reused
for every channel until the binding changes. The producer runs at most
APIOME_MOCK_BROKER_PRODUCER_DB_CONCURRENCY statements at once.
Stateful sessions on PostgreSQL. With APIOME_MOCK_SESSION_STORE_BACKEND=postgres, each
X-Mock-Session has one row in mock_session. That row holds the session's expiry, its last
activity, its resource count and its size, and the resources reference it. A read is one statement
that finds the session by its key and reads only that session's resources. It extends the expiry
only when the last extension is more than a minute old (or a tenth of
APIOME_MOCK_SESSION_TTL_SECONDS, if that is shorter). Reads never rewrite resource rows, and a
read does not wait for a write to the same session. Each create, update, delete or fixture-pack
reset runs in one transaction that locks the session's row first. Concurrent creates therefore
get distinct ids, and ids and sequence-scenario call numbers come from a counter row per
collection. A fixture pack is stored with one multi-row INSERT. A new session is checked against
APIOME_MOCK_SESSION_MAX_SESSIONS with a one-row count kept by a trigger, so the limit holds across
replicas and the table is never counted. Expired sessions are already invisible to requests. A
sweep on every replica deletes them every APIOME_MOCK_SESSION_PURGE_INTERVAL_SECONDS, in batches
of APIOME_MOCK_SESSION_PURGE_BATCH_SIZE taken with SKIP LOCKED. Until it runs, an expired
session still counts toward the limit, unless the same token is used again. The default memory
backend is unchanged.
Consumer captures. A call tagged for a consumer (Capture for a consumer)
is queued in memory and costs the request no statement. Every
APIOME_MOCK_CONSUMER_CAPTURE_FLUSH_INTERVAL_SECONDS, the runtime redacts what is queued and writes
it in one transaction, however many calls arrived. A graceful shutdown writes what is waiting. A
failed write keeps its calls for the next one, up to three tries. At most
APIOME_MOCK_CONSUMER_CAPTURE_MAX_PENDING calls wait; past that a tagged call is answered
not-recorded. A capture URL's token is looked up once and cached for
APIOME_MOCK_CONSUMER_CAPTURE_LINK_CACHE_TTL_SECONDS, so a revoked link stops within that time.
Expired captures are hidden from every read, and each replica deletes them every
APIOME_MOCK_CONSUMER_CAPTURE_PURGE_INTERVAL_SECONDS, in batches.
Cache invalidation. The runtime listens on APIOME_MOCK_SPEC_NOTIFY_CHANNEL. When that
connection drops, it reconnects with backoff, from 0.5 seconds up to 30 seconds, without a restart.
Every time it connects, it empties its caches, because changes made while it was disconnected were
never heard.
| Setting | Default | What it does |
|---|---|---|
APIOME_MOCK_DATABASE_POOL_MIN_SIZE / _MAX_SIZE | 1 / 10 | Connections the pool keeps open and may open |
APIOME_MOCK_DATABASE_POOL_TIMEOUT | 30 | Seconds a request waits for a connection |
APIOME_MOCK_DATABASE_POOL_MAX_WAITING | 100 | Requests that may wait for a connection; past it a new one fails at once. 0 means no limit |
APIOME_MOCK_DATABASE_STATEMENT_TIMEOUT_MS | 30000 | How long one statement may run. 0 turns it off |
APIOME_MOCK_DATABASE_APPLICATION_NAME | apiome-mock | The pool's name in pg_stat_activity |
APIOME_MOCK_ACCESS_CACHE_TTL_SECONDS | 5 | Seconds a version's on/off, visibility and mode are reused. 0 reads them on every request |
APIOME_MOCK_API_KEY_CACHE_TTL_SECONDS | 30 | Seconds a key that passed skips the lookup and bcrypt. 0 checks on every request |
APIOME_MOCK_API_KEY_NEGATIVE_CACHE_TTL_SECONDS | 10 | Seconds a key that failed is refused without a lookup |
APIOME_MOCK_USAGE_FLUSH_INTERVAL_SECONDS | 2 | Seconds between usage writes |
APIOME_MOCK_LIMITS_CACHE_TTL_SECONDS | 60 | Seconds a workspace's limits, or the fact that it does not exist, are reused |
APIOME_MOCK_MONTHLY_USAGE_CACHE_TTL_SECONDS | 30 | Seconds the month's usage total is reused between reads |
APIOME_MOCK_UNKNOWN_TENANT_RPS | 5 | Requests per second one client address may make to workspaces that do not exist |
APIOME_MOCK_BROKER_PRODUCER_DB_CONCURRENCY | 2 | Statements the Kafka producer runs at once |
APIOME_MOCK_SPEC_CACHE_MAX_ENTRIES | 256 | Compiled specs each cache keeps (REST, and event, gRPC and GraphQL). Was 128 |
APIOME_MOCK_SPEC_CACHE_TTL_SECONDS | 300 | Seconds before a compiled spec is checked for changes. An unchanged spec is kept |
APIOME_MOCK_SESSION_PURGE_INTERVAL_SECONDS | 60 | Seconds between sweeps of expired X-Mock-Session state (PostgreSQL store only) |
APIOME_MOCK_SESSION_PURGE_BATCH_SIZE | 500 | Expired sessions one sweep statement deletes; a sweep repeats full batches |
APIOME_MOCK_CONSUMER_CAPTURE_FLUSH_INTERVAL_SECONDS | 2 | Seconds between writes of consumer-tagged captures |
APIOME_MOCK_CONSUMER_CAPTURE_MAX_PENDING | 10000 | Tagged calls that may wait for a write; past it a call is answered not-recorded |
APIOME_MOCK_CONSUMER_CAPTURE_LINK_CACHE_TTL_SECONDS | 30 | Seconds a capture URL's lookup is reused; a revoked link stops within it |
APIOME_MOCK_CONSUMER_CAPTURE_PURGE_INTERVAL_SECONDS | 300 | Seconds between sweeps of expired consumer captures |
APIOME_MOCK_CONSUMER_CAPTURE_PURGE_BATCH_SIZE | 1000 | Expired capture rows one sweep statement deletes |
Measured on a scratch PostgreSQL 18 database, one hot public version, GET with 16 concurrent
clients and 15,000 requests, before and after these changes. The usage totals matched the requests
served both times:
| Request | Before | After |
|---|---|---|
| Hosted REST mock, cached, no key | 2 statements and 2 checkouts per request; 4,680–4,810 requests/s | 0 statements and 0 checkouts per request (1 batched usage write every 2 s); 11,410–12,560 requests/s |
Spec loading was measured on the same kind of database with a 500-operation published spec and a freshly started process. Times are from the first request to the last response, over three to seven runs:
| Cold version | Before | After |
|---|---|---|
| One request | 38–55 ms (median 42) | 29–40 ms (median 33) |
| 100 requests at once | 570–610 ms; every request loaded the spec itself, all 10 connections busy | 130–145 ms; one load and one connection |
| Unchanged spec after the cache time | Reloaded | 1 statement, kept |
The PostgreSQL session store was measured on a scratch PostgreSQL 18 database holding 100,000 sessions and 2,000,000 stored resources, 8,763 of those sessions already expired:
| Statement | Before | After |
|---|---|---|
| Start of every operation | Deleted every workspace's expired rows: 188,700 rows, 132 ms | Nothing; the sweep deletes 500 expired sessions per statement in 7 ms, by index |
| Read of one resource | Rewrote the expiry of all 20 of the session's rows | At most one session row, about once a minute |
| New session | Counted the distinct sessions of the whole table: sequential scan of 1,811,300 rows, 6.7 s | Reads the one-row count: under 0.1 ms |
| Next id | Read every id of the collection, and did not save it (sequence scenarios stayed on their first response) | One upsert of a counter row: 0.5 ms |
| Fixture-pack reset | One INSERT per resource | One multi-row INSERT |
What the web app reuses within a request and on Home
The web app reads your session, your workspace membership, the workspace's slug and your permissions once per page load or action, and reuses them for every check in that request. A sign-in, sign-out or workspace switch during the request is read afresh. Nothing is kept between requests, so a change to a member or a role applies on the next page load.
The counts in Home's stat strip and the /ade launcher (projects, revisions, classes and
properties across your workspaces) are cached for 60 seconds per person in each web app
process. A change can take up to a minute to show there. Every other Home panel is read on each
load.
Behind those counts, the table apiome.version_content_counts stores each revision's class and
property counts, taken at the revision's content stamp. Only revisions changed since they were
last counted are counted again. The table is a cache: you can empty it with
TRUNCATE apiome.version_content_counts;, and the next Home load fills it again. That first load
counts every revision, which takes about half a second for a workspace of 50,000 revisions.
Domains, sign-in redirects and the session cookie
The web app and Studio share one sign-in. Two things follow from the hostnames you deploy them on:
- The session cookie is scoped to the installation's registrable domain — the part of the
hostname you own. For
app.example.comthat is.example.com; forapp.example.co.ukit is.example.co.uk. The cookie that remembers a person's active workspace uses the same domain, so the workspace chosen on the web app is the one Studio opens, and the other way round; signing out on either clears it on both. - After sign-in, a person can be sent to any
httpshost under that same domain, or to one of the app URLs you configured (BETTER_AUTH_URL,NEXT_PUBLIC_MAIN_APP_URL,NEXT_PUBLIC_STUDIO_URL). Any other address is replaced with the default landing page.
Apiome finds the registrable domain with the Public Suffix List, so a shared hosting domain is never mistaken for yours:
| The app is served from | Cookie domain | Also trusted after sign-in |
|---|---|---|
app.example.com | .example.com | every https host under example.com |
app.example.co.uk | .example.co.uk | every https host under example.co.uk |
apiome.vercel.app | .apiome.vercel.app | hosts under apiome.vercel.app only — not other *.vercel.app sites |
BETTER_AUTH_COOKIE_DOMAIN overrides the cookie domain. Set it only to a domain you own: a value
that does not match the app URLs, or that is a public suffix such as .co.uk or .vercel.app, is
ignored and the domain is worked out from the app URLs instead.
Two consequences for how you lay out hosts:
- Put the web app and Studio under one domain you own (
app.example.comandstudio.example.com) to share a sign-in between them. On a hosting platform's shared domain they are separate sites: the session cookie is not shared between them, and Studio is a trusted destination only whenNEXT_PUBLIC_STUDIO_URLnames it. - Every host under your domain is inside the sign-in boundary. A forgotten DNS record that points at a service you no longer run can be claimed by someone else, and would then receive the session cookie. Remove DNS records when you retire a host, and review the records under the domain from time to time.
What sign-in does when the database is unreachable
Each time a session is read, Apiome checks the person's active workspace against their memberships in the database. If that check cannot run — the database is down or unreachable — the session is given no active workspace rather than the one the browser remembers, because the remembered value comes from a cookie and cannot be trusted unchecked.
People stay signed in, but pages that need a workspace cannot load until the database answers
again. Nothing has to be reset afterwards: the next request restores the workspace. The web app's
log records each failed check as [post-login-routing] membership lookup failed.
Sign-up security check
The email sign-up form can carry a Cloudflare Turnstile
check, so scripts cannot create accounts in bulk. It is off by default. To turn it on, add a
Turnstile widget for your Apiome domain in the Cloudflare dashboard, then set both keys in
apiome-ui/.env and restart apiome-ui:
| Variable | What it is |
|---|---|
TURNSTILE_SITE_KEY | The widget's public site key; the browser draws the check with it |
TURNSTILE_SECRET_KEY | The widget's secret key; apiome-ui checks each answer with Cloudflare |
With only one of them set, the check stays off. While it is on, Create account waits for the
check, and the form is refused if Cloudflare does not confirm the answer — or cannot be reached.
Provider sign-up and Resend email never show it. Refusals are listed under
Recent blocked sign-ups; they reach it only when
INTERNAL_SERVICE_TOKEN is set on apiome-ui and apiome-rest, like every sign-in event. The same token,
set on apiome-mcp as APIOME_MCP_REST_INTERNAL_SERVICE_TOKEN, turns on
export over MCP.
Email for notifications
The REST API emails some notifications — today, catalog
drift email. It sends with SendGrid, like email
sign-up in the web app. Set both in apiome-rest/.env (or the rest service's environment) and
restart apiome-rest:
| Variable | What it is |
|---|---|
SENDGRID_API_KEY | The SendGrid key Apiome sends email with — the same key as apiome-ui's |
EMAIL_FROM | The sender address, for example Apiome <no-reply@apiome.example> |
APIOME_UI_PUBLIC_URL | The public address of the web app, which the links in an email point at |
With either of the first two missing, nothing is emailed and nothing fails: the other channels of a notification still go out. A refused or failed send is logged by apiome-rest without the message.
Largest spec the import wizard accepts
The Import wizard on Projects and Versions sends the whole parsed spec to apiome-ui in
one request, which is capped at 25 MB by default. A larger spec fails with Body exceeded … limit.
To raise the cap, set APIOME_SERVER_ACTION_BODY_LIMIT (for example 50mb) in apiome-ui/.env
before building apiome-ui. The value is baked into the build, so rebuild the image after
changing it. Import to catalog uploads through the REST API instead and is not affected.
Imports waiting for review
The Import specification wizard writes an import and then waits for the reviewer to click “Accept & commit” or “Reject & rollback”. While it waits, the import is saved in the database but hidden, and it holds no database connection. Any number of imports can wait at once without using the web app's connection pool.
| Setting | Service | Default | What it does |
|---|---|---|---|
IMPORT_PENDING_TTL_MINUTES | Web app | 60 | How long an import waits for a decision. After that the web app deletes it, and the reviewer has to run the import again. |
Set it in apiome-ui/.env and restart the web app. DB_IDLE_IN_TRANSACTION_TIMEOUT_MS no longer
limits a review: before, a review that took longer than that setting (60 seconds by default) lost
the import.
The web app looks for imports past the limit when it starts, and then every quarter of the limit (at least every minute, at most every 15 minutes). An import whose reviewer closed the browser, or that was waiting when the web app restarted, is removed the same way, once it is older than the limit. Each web app instance runs the check, and they do not get in each other's way.
To see what is waiting:
SELECT v.id, p.slug AS project, v.version_id, v.import_pending_at,
now() - v.import_pending_at AS waiting_for
FROM apiome.versions v
JOIN apiome.projects p ON p.id = v.project_id
WHERE v.import_pending_at IS NOT NULL
ORDER BY v.import_pending_at;
A waiting import has deleted_at set on its version, and on its project when the import created
the project. That is what hides it. It is not a deleted project: Show deleted does not list it,
and it cannot be restored or permanently deleted. Do not clear deleted_at by hand; let the
reviewer accept the import, or let the limit pass.
This needs migration V411. Apply it before you start the new web app: the import fails with
column "import_pending_at" does not exist otherwise.
Document store
The REST API keeps unchanging files — the original document of every import, and export
downloads above the database threshold — in the document store. APIOME_DOCUMENT_STORE on the rest service picks where:
| Value | Objects are kept in | Also set |
|---|---|---|
db (default) | The database | Nothing |
s3 | An S3-compatible bucket (AWS, MinIO, Garage, R2) | APIOME_DOCUMENT_STORE_BUCKET, and …_ENDPOINT_URL for anything other than AWS |
filesystem | A directory on the REST host | APIOME_DOCUMENT_STORE_PATH |
APIOME_DOCUMENT_STORE_PREFIX (default apiome) is the folder all objects are written under, in
any backend. Document store lists every setting, with examples for Garage,
MinIO, R2 and AWS.
The REST API checks the store at startup and refuses to start when it cannot be used, unless
APIOME_DOCUMENT_STORE_FALLBACK=db is set. /health reports it under document_store, and the
admin console's Document store page has Test connection — see
Check the store.
Every hour the REST API also deletes stored files no live version uses any more (after a 24-hour grace period), empties the folders of deleted tenants, and re-hashes a sample of files to check they are unchanged — see Retention and integrity.
Agent runtime address in server.json
The server.json export gives hosts the agent
runtime's public address and tells them how to sign in. Set these in apiome-rest/.env (or the
rest service's environment) and restart apiome-rest:
| Variable | Default | What it is |
|---|---|---|
APIOME_AGENT_MCP_PUBLIC_URL | http://localhost:8765/agent/mcp | The public http(s) URL of apiome-mcp's agent runtime (/agent/mcp). Anything else makes the export answer 503 |
APIOME_AGENT_MCP_PRM_URL | empty | The runtime's OAuth Protected Resource Metadata URL. When it is set, the export tells hosts to use OAuth. When it is empty, it tells them to use an agent key |
Agent telemetry
The agent runtime can export every agent tool call as OpenTelemetry traces and metrics. It is off
until APIOME_MCP_OTEL_EXPORTER_OTLP_ENDPOINT is set on the mcp service. See
Agent telemetry for every setting and for Datadog, Grafana and Honeycomb
recipes.
Keys that encrypt stored secrets
Some settings are encryption keys: they seal a secret before it is written to the database, so a copy of the database on its own does not reveal it. Each is optional at start-up, and each fails closed — without the key the secret is not stored, never stored unencrypted.
| Variable | Set in | Encrypts |
|---|---|---|
APIOME_LINKED_ACCOUNT_TOKEN_ENCRYPTION_KEYS | apiome-ui and apiome-rest (identical) | The sign-in tokens and personal access tokens of linked accounts |
AUTH_CONFIG_ENC_KEY | apiome-rest | Client secrets saved on Sign-in providers |
APIOME_MCP_CREDENTIAL_ENCRYPTION_KEYS | apiome-rest | Credentials for protected MCP servers |
APIOME_SDK_REGISTRY_CREDENTIAL_ENCRYPTION_KEYS | apiome-rest | npm and PyPI publish tokens |
APIOME_UPSTREAM_CREDENTIAL_ENCRYPTION_KEYS | apiome-rest | Credentials a managed MCP toolset presents to your API |
APIOME_SLATE_CDN_CREDENTIAL_ENCRYPTION_KEYS | apiome-rest | CDN purge credentials (Cloudflare, Fastly, custom) for hosted Slate sites |
APIOME_BROKER_CREDENTIAL_ENCRYPTION_KEYS | apiome-rest | SASL credentials of the Kafka clusters tenants bind their AsyncAPI mocks to (Event mock brokers) |
Each …_ENCRYPTION_KEYS value is a JSON object that maps a key version to a base64-encoded
32-byte key. Single-quote it in a .env file:
APIOME_LINKED_ACCOUNT_TOKEN_ENCRYPTION_KEYS='{"1": "<base64 key>"}'
Generate a key with:
python3 -c "import base64, os; print(base64.b64encode(os.urandom(32)).decode())"
Store these keys in your secret manager. A lost key cannot be recovered, and the secrets it sealed have to be entered again.
Linked-account tokens
The web app encrypts a linked account's tokens when it saves them, and the REST API decrypts them
to read a repository, so both must hold the same APIOME_LINKED_ACCOUNT_TOKEN_ENCRYPTION_KEYS.
When the key is not set, people can still sign in and link providers, but:
- no provider token is stored, so scans and imports of private repositories report a missing token;
- saving a Personal Access Token is refused, with a message that names the variable.
An account linked during that time has no stored token. After you set the key, its owner adds a Personal Access Token, or unlinks the provider and links it again.
Upgrading an installation that already has linked accounts. Tokens saved before this
encryption existed stay readable, and stay unencrypted until you seal them. After you set the key
in both services and deploy, run this once in the rest service (docker compose exec rest …), or
from apiome-rest in a source checkout:
python -m app.seal_linked_account_tokens --dry-run # reports counts, changes nothing
python -m app.seal_linked_account_tokens
The command prints counts only and is safe to run again. The
Production deployment (docs/runbooks/PRODUCTION_DEPLOY.md)
runbook has the Compose form of these steps.
Rotating the key. Add a higher version to the map in both services —
'{"1": "<old key>", "2": "<new key>"}' — deploy, and run the same command. It re-encrypts every
token under the newest version. Remove the old version once the command reports
"tokens_resealed": 0.
Runbooks
| Runbook | Use it to |
|---|---|
Production deployment (docs/runbooks/PRODUCTION_DEPLOY.md) | Promote the Compose stack to an HTTPS deployment with gated migrations and a rollback |
Backup and disaster recovery (docs/runbooks/BACKUP_AND_DR.md) | Take, verify and restore backups, and run DR drills |
Private beta triage (docs/runbooks/BETA_TRIAGE.md) | Triage feedback and incidents from beta and dogfood users |
Database performance
Apiome stores specifications as rows, so its tables reach millions of rows quickly. The services are built to stay fast at that size: each request runs a small, fixed number of statements, lists read one page at a time, and queries use their indexes. Four things are yours to set and watch.
| What | Settings | Where it is described |
|---|---|---|
Pool sizing. Keep the connections every service may open below PostgreSQL's max_connections. | DB_POOL_MAX_IN_USE, DB_POOL_MAX, REQUEST_THREAD_POOL_SIZE, the MCP and mock pool sizes | Database connections |
| Statement timeout. A statement that runs too long fails instead of holding its connection. | DB_STATEMENT_TIMEOUT_MS (30000), DB_LONG_STATEMENT_TIMEOUT_MS, DB_LOCK_TIMEOUT_MS, DB_IDLE_IN_TRANSACTION_TIMEOUT_MS | Limits on a stuck session |
| Slow-query visibility. See which statements cost the most, and the plans of slow ones. | pg_stat_statements, POSTGRES_AUTO_EXPLAIN_MIN_DURATION, APIOME_DB_STATEMENT_WARN_THRESHOLD | Find slow queries |
| The scale seed profile. Check a change against a large database before it reaches yours. | apiome-db seed --profile scale, apiome-db plan-check | Benchmark against a large database |
When the app slows down:
- Look at the sessions with the
pg_stat_activityquery under Limits on a stuck session. A sessionidle in transactionthat blocks others is the usual cause. - Find the costly statements in
pg_stat_statements, and the heavy requests bydb_statementsin the REST API's access log. See Find slow queries. - Check the pool sum against
max_connections. A503with error typedatabase_busymeans one API instance reachedDB_POOL_MAX_IN_USE;statement_timeoutmeans one statement ran pastDB_STATEMENT_TIMEOUT_MS.
Some answers are cached for a short time so they are not read again on every request: sign-in and permissions, the public directory, the MCP catalog and the mock runtime's specs. Each cache, and how long a change takes to show, is described in its own section above and below. Upgrades that build indexes or rewrite a large table are covered in Upgrade a large database without blocking writes.
Keep queries able to use their indexes
Compare a uuid column to a uuid parameter (id = $1::uuid, id = ANY($1::uuid[])); never cast the column to
text (id::text = …), because that hides the index and scans the table. Order version history by
created_at DESC NULLS LAST, id DESC to match idx_versions_project_created. The REST test suite
(tests/test_sargable_uuid_lint.py) fails on a new ::text cast of an id column; a lookup that must accept a slug
or an id is the only reason to add an allowlist entry there.
Walk version history with one recursive query, not a query for each step. Keep the ids as uuids
inside the recursion, cast them to text only in the final SELECT, and follow the two parent links
as two primary-key lookups (CROSS JOIN LATERAL (VALUES (parent_version_id), (merge_parent_version_id)))
rather than one OR join. The shared queries are in apiome-rest/src/app/revision_graph_sql.py.
Give every new foreign key an index led by its columns. Deleting the referenced row checks the
referencing table by that column, and without such an index the check scans the whole table, once for
each deleted row. An index that is partial on deleted_at IS NULL does not count, because the check
cannot use it. For a nullable column that is usually empty, use a partial index WHERE <column> IS NOT NULL:
the check can use it, and rows that leave the column empty cost nothing. The apiome-db schema test
(test/foreign-key-index-coverage.test.ts, run in CI on a migrated database) fails on a foreign key with
no usable index. The only exceptions are the references to users listed in
apiome-db/test/foreign-key-index-allowlist.json. Users are hard-deleted only by apiome-db users delete,
which accepts the scan.
What the browse site and the public directory API cache
The public directory is the same for every visitor. The browse site and the REST API therefore keep those answers in memory for a short interval instead of reading them for each page view or request. On the browse site a refresh reads the public-catalog summary table (see What the browse site reads for each page), so even a cold read is a few milliseconds.
| Setting | Service | Default | What it sets |
|---|---|---|---|
BROWSE_CACHE_TTL_SECONDS | Browse site | 120 | Seconds the browse site reuses the directory counts in its top bar and the lists on its home page. 0 reads them on every page view. Values above 300 are treated as 300. |
BROWSE_PUBLIC_CACHE_TTL_SECONDS | REST API | 120 | Seconds an API instance reuses the answers of GET /v1/browse/tenants. The response's Cache-Control: public, max-age carries the same number. 0 reads the database on every request and answers no-store. Values above 300 are treated as 300. |
BROWSE_PUBLIC_CACHE_MAX_ENTRIES | REST API | 512 | Most GET /v1/browse/tenants answers kept at once, one per distinct combination of search, sort, protocol, format, limit and offset. |
DB_POOL_MAX | Browse site | 10 | Connections one browse site process may hold. See Database connections. |
What is cached on the browse site: the organizations, projects and versions counts in the top bar, and the home page's organization list, Recently published, the project rail in each of its three orders, and New organizations. Each browse process refreshes them on its own clock, so two processes can show different counts for up to one interval. Everything else — an organization's page, a project, a version, search results — is read on each view.
What a visitor sees: a version published a moment ago can take up to the interval to be counted and to appear on the home page. Its own page, and search, show it at once.
When a refresh fails: the browse site keeps showing the previous counts and lists and tries again on the next page view. A failed read is never kept. The REST API returns the error and reads again on the next request.
Filter facets in search: the browse site computes the counts in the search page's filters rail with the first page of a search and reuses them for that search's following pages, for the same interval.
Two more things keep the browse site's statements short:
- Card counts are stored. The N operations · M schemas on a project card are read from
versions.operation_countandversions.schema_count. The database records them when a version is published, and clears them when it is unpublished or when one of its classes, paths or operations is written — a version published as editable, or a published version an administrator edits. While they are empty the card counts the rows itself, so the numbers are always right; a version gets its stored counts back the next time it is published. - The JIT compiler is off for the browse site's sessions (
jit = off). Every statement the site runs is a short read, and PostgreSQL's compiler added about 200 ms to some of them. The setting applies to connections namedapiome-browseonly.
What the browse site reads for each page
The public-catalog summary table. apiome.browse_public_projects (migration V431) holds one
row for each project that is in the public catalog: its organization, how many public versions it
has, which one is the latest, the protocols and formats it publishes, and the latest version's
operation count, schema count and grade. The browse site's home page, the counts in its top bar,
an organization's project list and the scope of a search read this table. Before, each of them
passed over every published public version.
The database keeps the table current in the same transaction as the write: when a version is
published, unpublished, made public or private, deleted or restored, when its content or grade
changes, and when its project or organization is deleted or restored. Nothing needs to be
scheduled. If rows were ever written with triggers off (a restore with
session_replication_role = replica), rebuild the table with this statement, which is always safe
to run:
SELECT apiome.refresh_browse_public_projects(ARRAY(SELECT id FROM apiome.projects));
Statements per page. Each page of the browse site reads through one function that runs a
fixed number of statements, and a test holds every route to its number
(apiome-browse/lib/db/statementBudgets.json):
| Page or route | Statements | What changed |
|---|---|---|
Organization (/tenant/<org>) | 3 | The organization is found with one index probe. It took 32 ms for an organization with 5,000 projects. |
| Project | 2 | The version list carries each version's severity. Before, the page read the full changelog of 50 versions for it. |
| Version | 1 | One statement. The Changes tab reads its entries when it is opened, with 1 more statement. |
| Changelog page | 3 | 20 versions a page, filtered in the database. Before, it read up to 500 full changelogs and filtered them in the page. |
| Compare | 3 | One changelog row for the pair being compared, without its entries. |
Changelog feeds (changelog.xml, changelog.json) | 1 when unchanged, 2 otherwise | A reader that sends If-None-Match gets 304 from one small query. |
Try It (POST /api/try-it) | 1, then 0 for 30 seconds | See below. |
| API product | 4 | Each member API reads at most 200 version labels. |
| MCP server | 2 | The server's tools, resources and prompts are read once. |
| MCP collection | 2 | Read once for the page and its title. |
MCP index (/mcp) | 1 | 100 servers a page. |
What a visitor sees:
- Changelog page: 20 versions at a time, with Older versions → and ← Newest versions under the list. The filters apply to every page.
- Project page: the newest 200 versions. A project with more says so and points to the changelog, which has them all.
- Search: a result's version menu lists the project's newest 20 versions and ends with Show all versions when there are more. The MCP servers tab shows its count once it is opened. Each kind of result is counted up to 1,000, so a common word no longer hides organizations and projects behind thousands of properties.
- MCP index: ← Previous and Next → under the list.
Try It and the 30 seconds. The relay looks up whether the version is public, whether its mock
is on and which servers its spec declares, and reuses that answer for 30 seconds. So after a
version is unpublished, its mock is switched off or its servers change, the relay can apply the
previous answer for up to 30 seconds. It never uses an answer older than that: if the lookup fails,
the relay answers 503.
When the database cannot answer. A page whose data could not be read used to answer 404, so
a full connection pool told search engines that the pages they asked for were gone. Now:
| Situation | What the browse site answers |
|---|---|
| Every connection in the pool is in use, and as many requests again are waiting for one | 503 with Retry-After: 5, before the page is rendered |
| A statement could not get a connection (the pool timed out, PostgreSQL refused or dropped it) | 500 for that request, then 503 with Retry-After: 5 for the next 5 seconds |
One statement ran past DB_STATEMENT_TIMEOUT_MS | 500 for that page (the error page, with Try again); other requests are not affected |
| A feed, the Try It relay or a search API route could not read the database | 503 with Retry-After: 5 |
| The page really does not exist | 404, as before |
A 503 from the first two rows carries the header X-Apiome-Shed (saturated or unavailable),
so you can tell them apart in an access log. If you see saturated, raise DB_POOL_MAX or add a
browse site instance; see Database connections.
Measured on the scale database (20,000 projects, 5,000 of them public; PostgreSQL 18), one statement each:
| Statement | Before | After |
|---|---|---|
| Directory counts in the top bar | 13.9 ms | 0.5 ms |
| Home page organization list | 15.1 ms | 3.1 ms |
| Home project rail, Most versions | 8.4 ms | 0.5 ms |
| Home project rail, Most operations | 17.0 ms | 0.4 ms |
| Home project rail, Best grade | 16.4 ms | 0.4 ms |
| Find an organization with 5,000 projects | 6.9 ms | 0.1 ms |
Search with an org: filter | 22.9 ms | 2.9 ms |
Search with an org: filter, every version | 33.1 ms | 5.1 ms |
| MCP index, 1,000 public servers | 19.4 ms, 491 kB | 4.5 ms, 53 kB (one page) |
| Changelogs for a changelog page, a project with 509 versions of 100 changes each | 33.1 ms, 21 MB read | 13.7 ms, 162 kB read |
| Changelogs for a project or compare page, the same project | 4.3 ms, 2.1 MB read | 0.6 ms and 0.2 ms, 114 kB read |
| Version menus for one search result, the same project | 1.4 ms, 45 kB | 0.6 ms, 2 kB |
A search for a word that matches a great many names can take longer than before. It used to stop after the first 5,000 matches of any kind, which is how results went missing; it now reads every kind up to its own limit.
What the MCP catalog stores and caches
Every discovery of an MCP server writes a snapshot, and a snapshot never changes. The catalog therefore stores what it used to work out on each page load, on the snapshot itself: how many tools, resources, resource templates and prompts it has, whether a tool is destructive, whether every tool is read-only, the largest number of parameters any tool takes, and how many changes the snapshot introduced. The MCP Catalog grid, its filters, Analytics and a server's Evolution chart read those stored facts.
| Setting | Service | Default | What it sets |
|---|---|---|---|
MCP_CATALOG_INSIGHT_CACHE_TTL_SECONDS | REST API | 30 | Seconds an API instance reuses one workspace's Analytics numbers (GET /v1/mcp/{tenant}/insight/catalog). 0 reads the catalog on every request. Values above 300 are treated as 300. |
MCP_CATALOG_INSIGHT_CACHE_MAX_ENTRIES | REST API | 1000 | Most workspaces whose Analytics numbers one instance keeps at once. |
What a person sees: after a discovery, a publish or a delete, Analytics can take up to 30 seconds to show it. The grid, the filter counts and every server page are read on each load and show it at once. The cache is per workspace, so nobody sees another workspace's numbers.
Snapshots from before the upgrade have no stored facts until the backfill reaches them. The catalog computes their facts from their tools as it did before, so the numbers are right at every moment; those servers are just slower to list until they are done.
- The backfill runs with the migration.
apiome-db migrateapplies the migrations and then fills the facts in batches of 500 snapshots, one transaction each. If it is interrupted, the nextapiome-db migratecontinues from where it stopped. On the scale database it filled 15,880 snapshots (535,000 tools, resources and prompts) in 5.5 seconds. - To run it yourself:
apiome-db backfill mcp-version-facts. Add--batch <n>to change the batch size. Run it if you apply migrations with another tool. - To check it:
apiome-db backfill mcp-version-facts --verifyprints how many snapshots still have no facts, and lists any snapshot whose stored facts differ from the ones recomputed from its tools. It exits with status1if it finds one. On a healthy database both numbers are0.
Snapshots stay write-once: the database refuses every update of a snapshot, except filling the facts of one that has none.
Upgrade a large database without blocking writes
Each apiome-db migration runs in one transaction, so an index it creates blocks writes to that
table while the index builds. On a small database that takes milliseconds. On a large one, build
the indexes yourself before you deploy:
- Open the migration script (for example
apiome-db/scripts/V381__index_hygiene_and_cascade_indexes.sql) and copy itsCREATE INDEX IF NOT EXISTSstatements. - Run each one against the database as
CREATE INDEX CONCURRENTLY IF NOT EXISTS, keeping the index name. A concurrent build does not block writes and cannot run inside a transaction, so run the statements one at a time. - Deploy as usual. The migration finds the indexes already there and skips them.
If a concurrent build fails it leaves an invalid index behind: drop it and run the statement again before you deploy.
Some migrations replace an index with a wider one (for example V413 to V417, which add the
indexes the DBP-1.11 plan check found missing). Build the new index concurrently as above; the
migration then only runs the DROP INDEX IF EXISTS of the one it replaces, which takes a brief lock
and does not wait for a build. Built in one transaction, V412 to V417 took 8 seconds on a scale
database of 200,000 versions with 200,000 to 1,000,000 rows in each table they index. Their largest
tables are versions, workflow_audit, slate_insight_logs, document_objects,
version_documents and tenant_repository_refresh_jobs. Plan for the slate_insight_logs trigram
index, which is the slowest to build.
V422 adds two stored columns to versions (lint_error_count and sunset_at, which Home and
the sunset timeline filter on). Adding a stored column rewrites the table, and reads and writes of
versions wait while it does. That took about a second for 200,000 versions on the scale
database. Schedule the upgrade for a quiet time. Its two indexes are on the new columns, so they
cannot be built ahead of the upgrade.
V424 (DBP-1.16) adds versions.operation_count and versions.schema_count, and five trigram
indexes that the browse site's search palette matches names with. The two columns are nullable, so
versions is not rewritten.
If an upgrade stopped at V424 with operator class "gin_trgm_ops" does not exist for access method "gin", update apiome-db and run apiome-db migrate again. The first release of V424
did not set its own search path, so it failed on a database upgraded from V418 or later. A
failed migration is rolled back and not recorded, so the run continues from V424. A database
where the first release of V424 succeeded needs nothing: its recorded checksum is still
accepted, and apiome-db repair is not needed.
On the scale database:
- Backfill: it counts every published version once: 10 seconds for 180,000 published versions. Writes to those rows wait for it.
- Indexes:
projects0.1 s (20,000 rows),classes1.2 s (1,000,000),class_properties1.6 s (3,100,000),version_path1.0 s (600,000),path_operation_description3.8 s (1,200,000). Build them concurrently as above to avoid blocking imports while they build. - Write cost afterwards: an import-sized insert (20,000 classes, 60,000 properties, 12,000
paths, operations and descriptions) took 7.9 s with the indexes and 6.8 s without: about 15 %
more. If imports matter more to you than property suggestions in the palette, drop
idx_class_properties_name_trgm, the largest of the five on the import path; property suggestions then come only from the most recently published versions.
V425 (DBP-1.17) adds the stored facts to mcp_endpoint_versions (see
What the MCP catalog stores and caches) and three
indexes. The columns are nullable, so the table is not rewritten, and the migration itself fills
nothing: the backfill runs afterwards in small transactions. The indexes are small — on the scale
database, with 15,880 snapshots and 4,000 endpoints, each is under 1 MB and builds in
milliseconds — so there is nothing to build ahead of time.
V426 (DBP-1.18) adds the columns the background sweeps pick their work by (see
Background sweeps, queues and retention): when each MCP
server, repository and catalog digest is next due, and each server's latest uptime check. The
columns are nullable, so no table is rewritten. The migration fills them in one pass over
mcp_endpoints, tenant_repositories and mcp_catalog_digest_configs and reads
mcp_endpoint_health_checks once. On the scale database with 52,000 servers, 1,000,000 checks and
50,000 repositories that took 1.4 seconds, most of it the repositories; writes to those tables wait
while it runs. Its nine indexes can be built ahead as above. The largest,
idx_mcp_discovery_jobs_terminal_endpoint, took 0.5 seconds for 1,000,000 discovery jobs.
V427 (DBP-1.19) replaces the row-level content-stamp triggers on 35 tables with statement-level
triggers; it changes no table and builds no index, so it applies in well under a second. Each
DROP TRIGGER and CREATE TRIGGER waits for a brief lock on its table, so apply it while no long
import runs. Bulk writes to a revision's classes, paths and operations now cost the same whether
they touch one revision or hundreds: 50,000 inserted classes spread over 500 revisions took the
same time with the trigger as without (the row-level triggers made it 3.1 times as slow). To go
back, follow the rollback notes at the top of the migration file.
V430 (DBP-1.26) replaces the mock runtime's mock_session_state table with mock_session
and its child tables (see
The mock runtime's database work per request).
Sessions that have not expired are carried over, with their resources and expiry, and expired rows
are dropped with the old table. On 100,000 sessions and 2,000,000 stored resources it took 8
seconds; a typical table is far smaller. Stateful requests to a mock runtime that is still on the
previous version fail between the migration and that runtime's restart, so upgrade apiome-mock
right after the migration. Only deployments with APIOME_MOCK_SESSION_STORE_BACKEND=postgres use
these tables.
V431 (DBP-1.27) adds the public-catalog summary table browse_public_projects and fills it (see
What the browse site reads for each page), and
stores each MCP server's host in mcp_endpoints.host. On the scale database it took 0.4 seconds
(45,000 public versions in 5,000 projects; 2,000 MCP servers). Storing the host rewrites
mcp_endpoints, which holds one row per registered MCP server, so reads and writes of MCP servers
wait for that moment. Afterwards a write to a published public version also updates its project's
summary row: one small statement per write statement, and none for a draft or a private version.
Upgrade the browse site right after the migration: the new browse site needs the table, and the
previous one keeps working without it. To go back, follow the rollback notes at the top of the
migration file.
A migration that adds a stored generated column cannot be prepared this way. V409 adds
properties.data_digest, which rewrites the properties table and blocks reads and writes of
project properties while it runs: about a second for each million properties. Apply it in a quiet
period on a large database.
V418 to V421 (DBP-1.12) index foreign keys and remove indexes that only cost writes. Together they
took 7 seconds on the scale database (1,000,000 classes, 500,000 usage_daily rows).
V418adds 166 foreign-key indexes. Build them concurrently as above, and the migration then only drops the 31 partial indexes they replace. The largest isidx_classes_version_id_fkonclasses.V419only drops indexes. Each drop takes a brief lock and does not wait for a build.V420adds the stored columntenant_repository_files.is_importable. LikeV409, it rewrites the table and blocks repository scans and file browsing while it runs.V421adds anidprimary key tousage_hourlyandusage_daily. It rewrites both tables, so usage ingest and the adoption views wait for it. Apply it outside peak ingest.
V428 (the MCP catalog's list order) adds a column to versions, fills it for every published
revision, and creates three indexes on versions, one of them the vector index. It took 84 seconds
on the scale database, most of it re-indexing 20,000 embeddings. To keep the index builds from
blocking writes, add the column yourself first (ALTER TABLE apiome.versions ADD COLUMN IF NOT EXISTS mcp_listed_at timestamptz), build idx_versions_mcp_public_listed,
idx_versions_mcp_project_listed and idx_versions_mcp_public_listed_embedding_hnsw concurrently
with the definitions in the script, then deploy.
V447 (PFX-6.1) makes the database refuse a Pact row that points at another workspace's row: a
webhook delivery naming another workspace's webhook, a webhook firing naming another workspace's
delivery, and a commit status naming another workspace's repository. It adds a UNIQUE (id, tenant_id) key to push_webhook_delivery_events and tenant_repositories, which builds an index
on each and blocks writes to that table while it builds, then checks every existing row against
the new references. Apiome never wrote a crossed row, so the check passes; if it fails with a
foreign-key violation, the row it names points across workspaces — send it to support rather than
deleting it. Build its three CREATE INDEX IF NOT EXISTS indexes concurrently as above to shorten
the upgrade; the two unique keys are built by the migration.
V448 (PFX-6.2) adds five empty tables for stale-pact remediation and verification
scheduling and widens two CHECK constraints: the
verification-result trigger gains scheduled, and contract webhooks may name four new events.
Re-adding each constraint checks every existing row of verification_result and pact_webhook
once while holding a lock on the table; nothing is rewritten. After the upgrade, the remediation
sweep runs every APIOME_PACT_REMEDIATION_INTERVAL seconds (default 300); set
APIOME_PACT_REMEDIATION_ENABLED=false to hold it. Workspaces start on Manual only, so no
scheduled verification runs until someone chooses a cadence and a verification target.
V449 (PFX-6.3) adds one index, idx_verification_result_tenant_window (tenant_id, created_at),
so Contract health reads a workspace's verification
results inside its window without scanning every workspace's. It changes no table. On a large
verification_result, build it concurrently first as above
(CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_verification_result_tenant_window ON apiome.verification_result (tenant_id, created_at)); the migration then skips it.
V450 (PFX-6.5) adds the workspace secrets table
pact_secret (sealed values only), a secret_refs column on pact_webhook (an empty array for
every existing webhook, no rewrite) and the secret kind for verification target credentials (a
CHECK swapped on verification_target; every existing row satisfies it). Secrets are sealed with
APIOME_MCP_CREDENTIAL_ENCRYPTION_KEYS, the key webhook secrets already use; nothing new to set.
V451 (PFX-6.4) lets a Pact Broker pacticipant have an owner team: it adds pacticipant to the
owner kinds of entity_owners and unowned_findings (two check-constraint swaps on small tables). It
changes no column or index. Re-publish requests opened afterwards record unowned rather than
unlinked when nobody owns the consumer.
V452 (PFX-6.6) adds two indexes on pact_publication so the
matrix stays fast at 100,000 versions:
idx_pact_publication_consumer_recent (consumer_id, created_at DESC, id) and
idx_pact_publication_provider_recent (provider_id, created_at DESC, id). It changes no table. On a
large pact_publication, build them concurrently first as above
(CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_pact_publication_consumer_recent ON apiome.pact_publication (consumer_id, created_at DESC, id), and the same for the provider one); the
migration then skips them.
Importing from another Pact Broker (PFX-6.7) adds no migration.
An import request (POST …/pact-migration/import) is read up to twice APIOME_PACT_MAX_BYTES, like
a bulk publish, and holds at most 100 records; a single pact over APIOME_PACT_MAX_BYTES is refused
as a publish would refuse it. Imported webhook URLs are checked against the same outbound-host
policy as webhooks created by hand. Only members with Pacts create and edit can import, and each
request writes one pacts.migration.import row to the access audit.
V459 (PFX-8.17) adds pact_migration_sync, the keep-in-sync
of a migration: one new table, nothing existing touched. While a sync is on it holds the source
broker's credentials sealed with APIOME_MCP_CREDENTIAL_ENCRYPTION_KEYS (the same master keys as the
credential vault); without a key, keep-in-sync cannot be switched on. A sweep runs the due passes
every APIOME_PACT_MIGRATION_SYNC_INTERVAL seconds (default 60), at most
APIOME_PACT_MIGRATION_SYNC_BATCH_SIZE (default 2) per tick, each an incremental copy from the old
broker; set APIOME_PACT_MIGRATION_SYNC_ENABLED=false to hold them. A sync whose source has not
answered for 24 hours switches itself off and deletes the credentials.
Find slow queries
Three tools show where database time goes: a statement counter in the apps, PostgreSQL's
pg_stat_statements, and auto_explain.
Statements per request
The REST API counts the SQL statements each request runs, and the time they take. Every
http_request line of its access log carries two fields:
| Field | What it is |
|---|---|
db_statements | Statements the request sent to PostgreSQL. |
db_time_ms | Their total time, in milliseconds. |
The count covers the statements the code sends. A single read or write is sent on its own, with no
BEGIN or COMMIT around it. Where several statements must succeed or fail together, the
BEGIN and COMMIT around them are not counted.
| Setting | Service | Default | What it does |
|---|---|---|---|
APIOME_DB_STATEMENT_WARN_THRESHOLD | REST API | 0 (off) | Logs a request that runs more statements than this at WARNING. |
APIOME_DB_STATEMENT_SERVER_TIMING | REST API | false | Also sends the count and time to the caller as a Server-Timing: db;dur=…;desc="N statements" response header. Leave it off on a public deployment: it describes the server's internals. |
DB_STATEMENT_WARN_THRESHOLD | Web app | 0 (off) | Logs a workspace server action that runs more statements than this. |
To find the heaviest endpoints, filter the access log for high db_statements. A request that runs
hundreds of statements is usually a loop that issues one query per row.
Project and version checks
Most endpoints that name a project or a version first check that it exists in your workspace. That check reads one row by its primary key and nothing else. The extra work happens only where the response shows it:
| Response | What it adds to the check |
|---|---|
Project detail, GET /v1/projects/{tenant}/{project} | The number of live versions, their mean quality score and grade, and the creator. |
Version detail, GET /v1/versions/{tenant}/{project}/{version} | The security score, the fork source, the upstream project, the creator, and the version's metadata. |
Editing or deleting a class, a path or an operation is one statement: the workspace check is part
of the UPDATE or DELETE, so db_statements counts it once. A project's own write is one
statement too. It checks the workspace and the expectedUpdatedAt you sent in the same UPDATE,
and reads the project again only to report a conflict.
Both checks are in the plan check below, as rest.project_core and rest.version_core.
Loading a version's paths and canonical model
Rendering a version's OpenAPI document, opening a path on the Studio canvas, applying a source change and loading a version's canonical model each read a fixed number of statements, however large the spec is. Paths, operations and their details are read one table at a time for the whole version, not one query per path and four per operation:
| Read | Statements |
|---|---|
| A version's paths and operations (document render, export) | 6 |
One path's operations, GET /v1/paths/{tenant}/{version}/{path}/full | 6, with the workspace check |
| Source apply: the current document, read under the version's row lock | 11 |
| A version's canonical model (services, operations, messages, channels, types, fields, agents, skills) | 8 |
First render of a version's document, GET /v1/versions/{tenant}/{project}/{version}/document | 19, with sign-in |
Lists that used to read one row per item read them in one statement too: the properties of every
class (the public JSON Schema, the component materialization preview, the relationship graph), the
classes of every version (GET /v1/classes/{tenant}), each project's published versions (xRegistry,
agents.json and llms.txt), operation keys for identity suggestions, MCP registry trust posture
and category suggestions, feedback threads' comments, and component head revisions.
On the scale database, a 1,000-operation spec's paths load in 6 statements and about 27 ms, down
from 4,251 statements and about 530 ms. The source-apply read of the 20,000-class version takes
12 statements and about 540 ms, down from 19,033 statements and about 2.5 s. db_statements in the
access log stays flat as a spec grows. If it climbs with the number of paths or operations, look
for a loop that reads one row at a time. The new reads are in the plan check as
rest.operations_for_version, rest.operation_responses_for_version and
rest.canonical_operations_for_version.
Writes that grow with a spec
Importing a spec, applying a source change, forking a version, committing a merge and publishing each send a fixed number of statements too. Every table is written with one statement that carries all its rows:
| Write | Statements |
|---|---|
| Import: the canonical model of a spec | 7 |
| Source apply: every row of a version | 18 |
| Source apply: a one-line edit, with the read of the current document | 24 |
| Fork a version into another project | 7 |
| Merge commit: copy the target's classes into the new revision | 3, plus one for each level of nested properties |
| Publish: freeze one JSON Schema per class | 6 |
A source apply writes only what the edit changes. A class or a path that the edit does not touch keeps its rows, so its canvas position, comments and links stay where they are. A changed class is updated in place. A changed path is deleted and created again. A class the edit removes is soft-deleted, as before.
On a local PostgreSQL 18 with a 20,000-class version, a one-line source edit takes about 1.2 s and writes 1 class and its 3 properties. Before, it took about 6 s and rewrote all 20,000 classes and 60,000 properties. A fork takes about 2.1 s, down from 12.3 s. A merge copy takes about 2.3 s, down from 5.8 s. Importing the canonical model takes about 2.8 s, down from 4.9 s. A database reached over a network saves more, because each statement that is no longer sent is a round trip saved.
To link a class property to the project property with the same definition, a source apply looks the
definition up by properties.data_digest. PostgreSQL keeps that column itself (migration V409),
so no backfill is needed. The lookup is in the plan check as rest.property_by_digest.
The import wizard
The Import specification wizard, and the paths import in the path designer, write each table with one statement too. A statement carries up to 5,000 rows, so a table with more takes one statement per 5,000.
| Step | Statements |
|---|---|
| Write and verify an import of 1,000 operations and 2,000 classes | about 30 |
| “Accept & commit” | 7 to 9 |
| “Reject & rollback” | 8 |
| Paths and security schemes alone | 15 |
Before, the same import sent about 19,500 statements. On a local PostgreSQL 18 it took about 1.6 s
and now takes about 0.7 s; the largest OpenAPI file of the import corpus
(24-advanced-combined-composition.yaml) went from 153 statements to 37, and from about 120 ms to
about 90 ms. A database reached over a network saves more.
The import no longer reads back what it wrote to verify it. One statement compares, for each class, the number of properties the database holds with the number the import expected, and returns only the classes that differ. The rows are read only to explain a difference in the import log.
Whether the plan has room for another project or version is one probe that stops at the limit. It
used to count every project or version of the workspace. Both reads are in the plan check, as
ui.plan_versions_at_limit and ui.import_class_lookup, with the sweep for imports past their
limit as ui.import_pending_sweep.
Usage ingest
A batch sent to POST /v1/tenants/{tenant}/usage/ingest runs a fixed number of statements, however
many operations, hours and status codes it covers. Each table it adds counts to is written with one
statement, and the field counts with two:
| Step | Statements |
|---|---|
| Read the source, the published revisions, the finalized days and the consumer bindings | 4 |
| Take the workspace's ingest lock, then check the daily cap and the finalized days, and read the bindings again | 3 |
| Add the counts: hourly calls, unmatched paths, unattributed clients, field presence (2), body samples, binding stamps (2) | Up to 8, one for each kind of count the batch has |
| Record the batch in the ledger and add it to the day's count | 1 |
A batch of 5,000 hourly rows runs 12 statements, the same as a batch of 10. Before, it ran one statement for each row.
Batches from the same workspace still write one at a time, so that two batches can't both get under
the daily cap. Only the writes wait for each other now. A batch is parsed, sampled, scrubbed and
matched to operations before it waits. If a day was finalized, or a consumer binding was added or
deleted, while the batch waited, it is matched again before it writes. An event on a finalized day
is rejected with day-finalized, as before.
The daily cap (usage_events_per_day) is checked against a counter, usage_tenant_day, which holds
each workspace's admitted events for today and yesterday. Migration V410 adds it and fills it from
the ledger. The same statement that records a batch in the ledger adds the batch to the counter, so
the two always match. Deleting a usage source no longer gives the day's quota back. During a rolling
upgrade, batches written by servers still running the old version aren't counted until those servers
are replaced.
On the scale database, with one workspace sending batches of 1,001 events, each batch holds the
workspace's lock for about 38 ms, down from about 430 ms. One sender ingests about 14,400 events a
second, up from about 2,250. Four senders for the same workspace ingest about 20,800 a second, up from
about 1,450. The check under the lock is in the plan check as usage.ingest_admission.
The usage tables aren't partitioned. Retention removes old rows in batches of 10,000 per table during the usage sweep, which takes 85 to 140 ms a pass on 1.2 million hourly rows. Each workspace keeps its data for its own retention period. Dropping a whole day's partition would only work for days past the longest retention of any workspace, so the per-workspace deletes would still be needed.
Reading a version's history
Merge previews, branch divergence, publish checks, change reports, changelogs, compatibility checks, successor redirects and source provenance all follow a version's parents back through its history. Each of these reads is now one statement, however long the history is:
| Read | Used by | Statements before | Now |
|---|---|---|---|
| Ancestors and merge base | Merge preview, revision graph | 1 | 1 |
| Branch divergence (ahead, behind, merge base) | GET /v1/versions/{tenant}/{project}/version-branches/{branch}/divergence | 1 | 1 |
| Previous published version | Publish checks, change report, changelog | 2 | 1 |
| Earlier versions for a transitive compatibility check | Compatibility policy | 2 | 1 |
| Successor redirect | A version request that follows successorRevisionId | 2 to 4 for each hop | 1 |
| The import a draft started from | GET /v1/versions/{tenant}/{project}/{version}/provenance | 2 for each ancestor | 1 |
| Source edits since that import | The same provenance request | 1 | 1, one row for each edited location |
Each step back to a parent reads one row by its primary key. Merges are followed too, and a version reached by two paths is read once. If damaged data ever made a version its own ancestor, the read still stops. Successor redirects stop after 32 hops, and the walk back to an import stops after 50 versions, as before.
Times on the scale database (200,000 versions, plus a 500-version history and a 400-version history with branches that merge each other):
| Read | Before | Now |
|---|---|---|
| Branch divergence | 10.8 ms | 3.1 ms |
| Previous published version (500 versions) | 5.7 ms | 1.7 ms |
| Earlier versions for a compatibility check (500 versions) | 5.3 ms | 1.7 ms |
| Successor redirect (32 hops) | 33.2 ms, 129 statements | 0.7 ms |
| The import a draft started from (50 versions) | failed | 0.6 ms |
| Source edits (5,000 edits of 40 locations) | 6.9 ms, 5,000 rows | 4.7 ms, 40 rows |
Ancestors and merge base were already fast after the uuid fix in
Keep queries able to use their indexes and are unchanged
(about 3 ms for 500 versions). Before this change, the provenance request failed with a server error for a
version that had no import of its own, such as a draft created from an imported version. It now walks
back to that import. The plan check covers these reads as rest.revision_closure,
rest.prior_published_baseline, rest.transitive_check_candidates and rest.branch_divergence.
Turn on pg_stat_statements and auto_explain
pg_stat_statements keeps running totals for every distinct statement. auto_explain writes the
plan of every statement slower than a threshold to the PostgreSQL log. Both must be loaded when
PostgreSQL starts.
Self-hosted (Docker Compose). The postgres service loads both. Set the auto_explain threshold
in .env:
| Setting | Default | What it does |
|---|---|---|
POSTGRES_AUTO_EXPLAIN_MIN_DURATION | 1s | Logs the plan of any statement slower than this. -1 turns it off. |
Then create the extension once, so you can read the statistics:
docker compose exec postgres psql -U postgres -d apiome \
-c 'CREATE EXTENSION IF NOT EXISTS pg_stat_statements'
Recreate the postgres container (docker compose up -d postgres) after you change the threshold.
Your own or a managed PostgreSQL. Set these server parameters, through a parameter group or flags if your provider manages the server, and restart:
shared_preload_libraries = 'pg_stat_statements,auto_explain'
pg_stat_statements.track = top
auto_explain.log_min_duration = 1s
Then run CREATE EXTENSION IF NOT EXISTS pg_stat_statements; as a role that may create
extensions. Many managed services load pg_stat_statements already. Leave
auto_explain.log_analyze off in production: it times every plan node of every statement, not only
the slow ones.
To see the statements that cost the most in total:
SELECT calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(total_exec_time::numeric, 1) AS total_ms,
left(regexp_replace(query, '\s+', ' ', 'g'), 120) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
SELECT pg_stat_statements_reset(); starts the totals again, for example before you measure a
change.
Benchmark against a large database
Plans that are fine on a small database can be slow on a large one. apiome-db builds a large
benchmark database and checks the hot queries' plans against it. Use a scratch database, never a
live one:
- Create and migrate an empty database:
apiome-db migrate --database-url <scratch-url>. - Build the scale profile:
apiome-db seed --profile scale --database-url <scratch-url>. It writes 20,000 projects, 200,000 versions, 1,000,000 classes and 3,100,000 class properties, with one tenant of 5,000 projects and one version of 20,000 classes. Expect a few minutes.--scale-factor 0.1builds a tenth. The rows are the same on every run, and a second run skips the steps that are complete. - Check the plans:
apiome-db plan-check --database-url <scratch-url>. It runs every query inapiome-db/plan-check/hot-queries.jsonwithEXPLAIN (ANALYZE, BUFFERS)and prints each query's time and plan. It fails when a plan scans a table of more than 10,000 rows sequentially, or when a query runs over its time budget. A query already known to be slow is listed with the ticket that fixes it and does not fail the check. A query can state the session settings its service runs with (the browse site'sjit = off) and name a sequential scan that is intended, with the reason; the report prints the reason, and the time budget still applies.
The same database runs every night in CI (Apiome DB Scale Plan Check). The job also holds the
REST API's hot endpoints to their recorded statement counts.
Repair items with no captured source
Exports, conversions and the schema test bench are built from the source file each catalog revision
captured at import. A revision without one cannot be exported, and its users are told to re-import
it. scripts/backfill_captured_sources.py repairs the revisions it can, from a copy that is still
stored:
- another revision of the same item in the same format, or
- the linked repository file a repository-imported item came from, re-read at its recorded branch and path.
A copy is only used when it re-imports to the exact fingerprint the revision recorded, so text from
a different version is never stored. A repository file is scrubbed under the workspace's secret-scrub
policy first. Revisions that recorded no fingerprint are left alone and reported as unverifiable.
Run it from apiome-rest, with a dry run first:
PYTHONPATH=src python scripts/backfill_captured_sources.py --dry-run
PYTHONPATH=src python scripts/backfill_captured_sources.py # every workspace
PYTHONPATH=src python scripts/backfill_captured_sources.py --tenant <tenant-uuid>
It prints how many revisions it scanned and repaired, and how many it could not repair and why
(unverifiable, no_copy), with one outcome per revision. Each repaired revision records where its
source came from in sourceBackfilledFrom. It is safe to run again.
Move documents to object storage
Imports, freezes and large exports write their files to the document store.
Data written before the store existed, or while APIOME_DOCUMENT_STORE=db, is still kept in the
database. scripts/migrate_documents_to_store.py moves it into the store you have configured:
| Source | Kept in the database as |
|---|---|
adapter_source | The original of a non-OpenAPI import (format_metadata.sourceContent; an archive is unpacked into its files) |
import_snapshot | The original of an OpenAPI or Swagger import (version_import_snapshots.source_text) |
frozen_schema | A frozen version's schema (version_spec_snapshots.content) |
export_artifact | An export download that has not expired (export_job_artifact.content) |
The move takes two steps, run separately. The first copies. The second, run only after you have checked the first, removes the database copies.
-
Configure the store. Set
APIOME_DOCUMENT_STOREtos3orfilesystemand restart the REST API (see Document store). Run the script with the same environment as therestservice. -
Check what would be copied. From
apiome-rest:PYTHONPATH=src python scripts/migrate_documents_to_store.py --dry-run -
Copy. Each file is written to the store, read back and checked against its SHA-256 and the database copy, then linked to its version. The database copies stay:
PYTHONPATH=src python scripts/migrate_documents_to_store.py # every workspacePYTHONPATH=src python scripts/migrate_documents_to_store.py --tenant <tenant-uuid> # one workspace -
Check the report.
failedmust be0. Each failed or skipped row is listed with its key and the reason. Fix the cause (usually the store's permissions) and run step 3 again; it picks up only what is left. -
Remove the database copies. Each stored file is read back again and compared byte for byte with its database copy, and the copy is removed only when they match:
PYTHONPATH=src python scripts/migrate_documents_to_store.py --purge-db-copies --dry-runPYTHONPATH=src python scripts/migrate_documents_to_store.py --purge-db-copies
Things to know:
- It is safe to run again. A finished row is never selected again, so a second run reports
"scanned": 0. - It resumes. After each batch the script records how far it got in
apiome.document_migration_checkpoints. If a run is stopped, the next run starts after the last finished batch and the report showsresumed_after. - It runs gently by default: one worker, 50 rows a batch and at most 20 rows a second, one
document in memory at a time. Change this with
--workers(up to 4),--batch-size(up to 500) and--rate(0for no limit).--sourcelimits the run to one source and can be repeated. - Only one run at a time. A second run, from the script or from another host, exits with
Another document migration run is in progress. - Versions are not changed. Rendered documents stay valid, and no version's content stamp moves.
- A different original wins. If a version already has a stored original that differs from its
database copy, the row is skipped (
original-differs) and nothing is overwritten. - On the
dbbackend the copy step only links what the database holds, and export downloads are skipped.--purge-db-copiesis refused, because thedbbackend keeps the database copies by design. - The script exits
0when no row failed,1when a row failed, and2when the run was refused or another run was in progress.
A platform administrator can also run the steps from the REST API. POST /v1/ops/document-migration
starts one in the background and answers 202; the body takes purgeDbCopies, dryRun, tenantId,
sources, rate, batchSize and workers. GET /v1/ops/document-migration shows whether a run is
going, the last run's report and every checkpoint. See the ops reference.
Watch exports
Before Export studio opens to everyone, watch how exports are doing. Sign in as a platform
administrator and open /v1/ops/dashboard on the REST API. The Export health card refreshes
every 5 seconds and shows:
| Row | Means |
|---|---|
| n% failed | Failed export jobs as a share of completed + failed ones. Canceled jobs count in neither. |
| alert | ok, firing, no-data (too few jobs in the window to judge) or off |
| success rate | Completed jobs as a share of completed + failed ones |
| last 15 min | How many of the jobs in the alert window failed |
| alert at | The failure rate and the fewest jobs the alert needs to fire (20% of 10+ jobs) |
| p95 job time | 95% of export jobs finished within this time (≤ 30 s), from when the job started running to its end. > 1800 s means the slowest jobs ran past the 30-minute job cap. |
| target failed | The five targets with the most failed jobs, with each one's failure rate |
GET /v1/ops/import-export returns the same numbers under export_health, with every target, its
failure codes and the duration histogram. The numbers are kept per server process and start again
from zero when it restarts, so with several replicas, check each one.
The failure-rate alert
The alert fires when, over the last 15 minutes, at least 10 export jobs completed or failed and
at least 20% of them failed. It clears when the rate drops back under 20%, or when fewer than 10 jobs
remain in the window. Each time it fires or clears, the REST API logs one export.failure_rate_alert
line (a warning when it fires), so a log-based alert rule can page on it:
grep '"event": "export.failure_rate_alert"' rest.log | jq '{state, window_failed, window_jobs, window_failure_rate}'
Change the thresholds on the REST API:
| Setting | Default | Means |
|---|---|---|
APIOME_EXPORT_FAILURE_ALERT_RATE | 0.2 | Share of failed jobs that fires the alert. 0 turns the alert off. |
APIOME_EXPORT_FAILURE_ALERT_MIN_JOBS | 10 | Fewest completed or failed jobs in the window before the alert can fire |
APIOME_EXPORT_FAILURE_ALERT_WINDOW_SECONDS | 900 | How far back the alert looks |
When it fires, the Export health card names the targets that fail most, and
GET /v1/ops/import-export gives each one's failure codes. The codes are explained in
Export a spec.
Watch MCP re-discovery
The REST API re-discovers cataloged MCP servers on a schedule: every tick it picks the servers whose discovery cadence has passed and discovers them again, a few at a time. To see how that is going, sign in as a platform administrator and call:
curl -H "Authorization: Bearer $TOKEN" \
"$APIOME_API/v1/ops/mcp-discovery-sweep?tenant_slug=$TENANT&limit=20"
The answer has four parts:
| Part | Holds |
|---|---|
config | Whether the sweep is on, its tick, the default cadence, how many servers it discovers at once, the per-server timeout, and how many days runs are kept |
last_run | The most recent tick; null before the first one |
runs | The last limit ticks (default 20, at most 200), newest first |
totals | The counters below, summed over those ticks, plus how many were halted or failed |
Each tick reports:
| Field | Means |
|---|---|
status | completed; halted when APIOME_MCP_DISCOVERY_ENABLED is off; failed when the tick itself stopped with an error; running while it is still working |
started_at, finished_at, duration_ms | When the tick ran and how long it took |
due | Servers whose cadence had passed |
dispatched | Discoveries the tick started |
coalesced | Due servers that were already being discovered, so the tick left them alone |
enqueue_failed | Due servers the tick could not start a discovery for |
checked | The tick's discoveries, and of those: changed (a new version), unchanged, failed — including servers that ran past the timeout — and in_flight (still running) |
avg_job_ms, max_job_ms | How long the tick's discoveries took |
The counts come straight from the discovery jobs each tick created, so they always match the job
history: checked is changed + unchanged + failed + in_flight, and it equals dispatched
unless a server has been deleted since.
Ticks are kept for 30 days. With several REST API replicas, each runs its own sweep and every tick is listed. Change the sweep on the REST API:
| Setting | Default | Means |
|---|---|---|
APIOME_MCP_DISCOVERY_ENABLED | true | false stops every scheduled re-discovery. Each tick is still listed, as halted. Discovering a server by hand still works. |
APIOME_MCP_DISCOVERY_MIN_INTERVAL | 60 | Seconds between ticks |
APIOME_MCP_DISCOVERY_DEFAULT_CADENCE | 3600 | Seconds between discoveries of a server with no cadence of its own |
APIOME_MCP_DISCOVERY_MAX_CONCURRENCY | 4 | Servers discovered at once |
APIOME_MCP_DISCOVERY_MAX_PER_TICK | 500 | Most due servers one tick picks; the most overdue go first, and the rest wait for the next tick |
APIOME_MCP_DISCOVERY_ENDPOINT_TIMEOUT | 150 | Seconds one server's discovery may take before it is counted as failed |
Each discovery that creates a new version also logs one mcp.version.created line from
app.mcp_change_events, with the server, the new version number, the change count and the event
id:
mcp event mcp.version.created endpoint=<id> version_seq=3 changes=2 event_id=<id>
When the workspace has webhook subscriptions, app.mcp_change_webhooks then logs how many deliveries
it queued:
mcp-change-webhook: enqueued 2 deliveries of mcp.version.created endpoint=<id> event_id=<id>
A subscription that cannot be queued is logged as mcp-change-webhook fan-out: failed to enqueue ….
A subscriber to that event that fails is logged as mcp event handler … failed; neither fails the
discovery. The event's fields are on How versions work.
MCP uptime checks
The REST API also checks every enabled, network-reachable MCP server for uptime and
latency. Each check is only the initialize
handshake, so it is much cheaper than a discovery, and it never changes a server's discovery
failures, backoff or quarantine. Checks older than 30 days are deleted as new ones run. Each tick logs
one line from app.mcp_health_sweep:
mcp health sweep: probed=12 recorded=12
| Setting | Default | Means |
|---|---|---|
APIOME_MCP_HEALTH_ENABLED | true | false stops every check. Badges then read Uptime unknown once their last check is a day old. |
APIOME_MCP_HEALTH_MIN_INTERVAL | 60 | Seconds between ticks |
APIOME_MCP_HEALTH_CADENCE | 300 | Seconds between checks of one server |
APIOME_MCP_HEALTH_MAX_CONCURRENCY | 4 | Servers checked at once |
APIOME_MCP_HEALTH_TIMEOUT | 10 | Seconds one check may take before it is recorded as down, with timeout |
APIOME_MCP_HEALTH_MAX_PER_TICK | 200 | Most servers one tick checks; the least recently checked go first |
MCP registry sync
An MCP registry connector re-syncs on the
connector sweep, with every other connector. A registry connector with no cadence of its own
re-syncs hourly; one with a cadence keeps it. APIOME_REFRESH_ENABLED=false stops it with the rest,
and APIOME_REFRESH_MIN_INTERVAL is still the shortest cadence.
| Setting | Default | Means |
|---|---|---|
APIOME_MCP_REGISTRY_SYNC_INTERVAL | 3600 | Seconds between syncs of an mcp-registry connector with no cadence of its own (at least 60) |
MCP registry search
A catalog search can also search an MCP registry and list its servers after the catalog's own
results, without the servers already in the catalog: over the REST API with
include_registry=true (details), and in the browse
app with Include MCP Registry (details).
Both use the official registry unless you set another. Set the URL to an empty value to turn
registry search off. The registry's host must be reachable from the server, and the REST call goes
through the same private-address guard as connectors.
| Setting | Where | Default | Means |
|---|---|---|---|
APIOME_MCP_REGISTRY_SEARCH_URL | apiome-rest | https://registry.modelcontextprotocol.io | Registry the REST search adds (its root; empty turns it off) |
APIOME_MCP_REGISTRY_SEARCH_TIMEOUT | apiome-rest | 5 | Seconds the registry gets to answer (up to 60). After that the search returns without it |
MCP_REGISTRY_SEARCH_URL | apiome-browse | https://registry.modelcontextprotocol.io | Registry the public /mcp/search page adds (empty turns it off). The page waits 4 seconds for it |
Background sweeps, queues and retention
The REST API runs its background work — re-discovering MCP servers, checking their uptime, refreshing repositories, sending catalog digests, delivering webhooks, pruning old rows — as sweeps that wake up on a timer. Each sweep finds its work through an index and takes at most one batch per tick, so an idle sweep costs a few index reads however large the workspace is. Work that is still due when a batch is full runs on the next tick, most overdue first.
| Setting | Default | Means |
|---|---|---|
APIOME_MCP_DISCOVERY_MAX_PER_TICK | 500 | Most MCP servers one discovery tick picks |
APIOME_MCP_HEALTH_MAX_PER_TICK | 200 | Most MCP servers one uptime tick checks |
APIOME_MCP_DIGEST_MAX_PER_TICK | 200 | Most workspaces one catalog-digest tick sends a digest to |
APIOME_REFRESH_MAX_PER_TICK | 200 | Most repositories one auto-refresh tick picks |
APIOME_REFRESH_SWEEP_CONCURRENCY | 4 | Repositories refreshed at once. One workspace's repositories still run one after another, so its polling quota stays exact. |
A repository's next refresh follows the shortest cadence of the repository and its enabled branch
rules, and never comes sooner than APIOME_REFRESH_MIN_INTERVAL. Changing a cadence or a branch rule
moves it at once.
Webhook delivery
Push webhooks (the ones a workspace subscribes to) and export webhooks are delivered by one sweep every 15 seconds. Each tick sends what is due on a small pool of workers and keeps going until nothing is due, then sleeps:
| Setting | Default | Means |
|---|---|---|
APIOME_WEBHOOK_DELIVERY_WORKERS | 8 | Deliveries in flight at once, for each of the two queues. Each worker uses a database connection only while it records an attempt. |
APIOME_WEBHOOK_DELIVERY_PER_TENANT | 2 | Most of those one workspace may hold, so a slow receiver delays only its own workspace's deliveries |
APIOME_WEBHOOK_DELIVERY_BATCH_SIZE | 50 | Deliveries taken from the queue at a time |
APIOME_WEBHOOK_DELIVERY_TICK_SECONDS | 60 | How long one tick keeps taking new deliveries. Deliveries already started then finish, and the rest wait for the next tick. |
Against a receiver that answers at once, one API instance delivered about 4,600 webhooks a minute
with the defaults. Several replicas share the queues safely: a delivery taken by one is skipped by
the others. A receiver that is slow or times out (30 seconds) holds at most
APIOME_WEBHOOK_DELIVERY_PER_TENANT workers; raise APIOME_WEBHOOK_DELIVERY_WORKERS if many
workspaces have slow receivers at once.
Catalog graph edges
A change to a consumer's contract, a repository binding, a conversion or an API product updates
only that entity's catalog graph edges, in the same transaction, and
leaves unchanged edges as they are. The nightly repair sweep still re-derives every edge of every
workspace. An edge's last_seen_at is the last time that sweep confirmed it or a change rewrote it.
Retention of operational rows
Two kinds of operational rows are pruned on the 5-minute retention tick, in batches, so a large first backlog is worked off over several ticks:
| Setting | Default | Means |
|---|---|---|
APIOME_MCP_DISCOVERY_JOB_RETENTION_DAYS | 30 | Finished MCP discovery jobs (completed or failed) older than this are deleted. Queued and running jobs are never deleted. 0 keeps them forever. |
APIOME_MCP_DISCOVERY_JOB_KEEP_PER_ENDPOINT | 20 | Each server's newest finished jobs kept whatever their age, so a server discovered rarely keeps its history |
APIOME_SLATE_RETENTION_BATCH_SIZE | 5000 | Rows deleted at a time when Slate request data passes its retention |
Slate request data — logs, traces and their spans, live-tail sessions, synthetic check results, security events and function invocations — is written with the date its lane's retention policy ends, and is deleted after that date. The Slate audit log has no retention.
Agent usage and MCP audit retention
apiome-mcp runs its own sweep, once an hour by default, for the agent invocation log, its daily
rollups and the MCP audit tables. With several apiome-mcp instances only one runs each tick; the
others skip it. It can also run from cron with apiome-mcp agent-usage sweep.
Each tick first brings the daily usage rollups up to date, one day at a time, and then deletes rows past their retention:
| Rows | Kept for | Set by |
|---|---|---|
Agent invocations (one per agent tools/call) | 7 days on Free, 30 on Paid, 90 on Sponsor | the license's agent_invocation_retention_days |
| Daily agent usage rollups | 90 days on Free, 395 on Paid, 730 on Sponsor | the license's agent_usage_rollup_retention_days |
| Body samples of agent calls | 7 days | fixed |
| Upstream credential uses | 90 days | APIOME_MCP_AGENT_UPSTREAM_USE_RETENTION_DAYS |
MCP reads of private revisions (mcp_access_audit) | 365 days | APIOME_MCP_ACCESS_AUDIT_RETENTION_DAYS |
Refused MCP tool calls (mcp_capability_denials) | 90 days | APIOME_MCP_CAPABILITY_DENIAL_RETENTION_DAYS |
A negative license value keeps a workspace's rows forever. An invocation is deleted only after its day's rollup is final, so usage charts never lose a call.
| Setting | Default | Means |
|---|---|---|
APIOME_MCP_AGENT_USAGE_SWEEP_INTERVAL_SECONDS | 3600 | Seconds between ticks. 0 turns the in-process sweep off (run the CLI from cron instead) |
APIOME_MCP_AGENT_USAGE_SWEEP_BATCH_SIZE | 10000 | Rows one delete removes. Each kind of row is deleted batch after batch, each committed on its own, until less than a batch is left |
APIOME_MCP_AGENT_USAGE_SWEEP_TIME_BUDGET_SECONDS | 300 | How long one tick keeps deleting. Every kind of row still gets one batch; the rest waits for the next tick |
APIOME_MCP_AGENT_USAGE_FINALIZE_GRACE_HOURS | 6 | Hours after a UTC day ends before its rollup is final. Must be longer than the longest agent call |
The rollup for today recomputes only the agent keys and tools that were called since the previous tick (less the grace period), so a quiet tick costs little however many calls the day holds. A tick with nothing to delete reads a few index pages per table.
On the scale database, one workspace sending 1,000,000 agent calls a day with a 2-day retention
kept its invocation log at 2.0 million rows, two days of calls, over five simulated days of hourly
ticks. Each tick took about a second and deleted the hour's 41,666 expired rows. Before migration
V429, a tick deleted at most 10,000 rows, 240,000 a day, so that log grew by about 760,000 rows a
day. Credential uses are deleted at about 590,000 rows a second.
The invocation log isn't partitioned. Each workspace keeps it for its own tier's retention, so
dropping a whole day's partition would only work for days past the longest retention of any
workspace. Heavy deletes leave dead rows behind, so check that autovacuum keeps up on
agent_invocations (n_dead_tup in pg_stat_user_tables).
Upgrading. Migration V429 adds an index to each of agent_invocations,
upstream_credential_uses, mcp_access_audit and mcp_capability_denials. The builds block writes
to those tables while they run. On a large database, create them first with
CREATE INDEX CONCURRENTLY (the names and definitions are in the migration's header).
Retention settings elsewhere: MCP uptime checks are kept 30 days (MCP uptime
checks), discovery sweep ticks 30 days (Watch MCP
re-discovery), and async jobs, quality-rank observations and schema test
suite runs follow their own APIOME_*_RETENTION_DAYS settings.
The operator screens
- The admin console — signing in, and the overview.
- Users, Tenants in the admin console, Licenses and Feature flags.
- Sign-in providers and Property templates.
These screens predate the Hive redesign; each page says so, and the redesign is tracked in #5272.