Introducing a new way to review your PRs.

Read the announcement

keephq / keep

The open-source AIOps and alert management platform

View on GitHub

22 documents · Updated Nov 23, 2026

docs / api-and-background-runtime

API and background runtime

Keep runs as a FastAPI service that exposes product and system APIs while sharing a runtime with schedulers, event consumers, and optional background workers. Its startup path prepares the database and configured resources, its request path applies identity and telemetry context, and its asynchronous path moves work that should not block an HTTP request to ARQ and Redis.

Runtime model

Service roles

The runtime has several cooperating roles. The API serves clients and accepts external events. In-process services handle scheduled workflow work and event subscription when their flags are enabled. ARQ workers handle queued work in a separate process, while the server-jobs process runs long-lived demo and uptime tasks beside the API.

RoleMain purposeCoordination point
FastAPI serviceServe product routes and system endpointsget_app and the application lifespan
In-process servicesStart the scheduler, event consumer, topology processor, and maintenance watcherAPI startup settings
ARQ workerProcess queued events and other selected tasksRedis queues and worker task pools
Server jobsRun demo-mode and uptime reporting threadsSeparate server_jobs_bg.py process

The roles are not interchangeable. Request code should return a client response, while event processing and periodic work can continue in a worker or service role. This split lets the API remain the boundary for clients without making every product action depend on one long request.

References: keep/…/api.py• L120-243 keep/…/arq_worker.py• L32-64 keep/server_jobs_bg.py• L12-47

Runtime flow

The following flow shows how an installation moves from process start to request handling and background work.

flowchart TD
    A[Process starts] --> B[Prepare database and resources]
    B --> C[Create FastAPI application]
    C --> D[Apply request context and middleware]
    D --> E[Serve route domain]
    E --> F{Work needs async processing?}
    F -->|No| G[Return API response]
    F -->|Yes| H[Queue ARQ job]
    H --> I[Redis]
    I --> J[ARQ worker]
    J --> K[Persist results and notify clients]

The process uses the database and resource preparation stage before workers serve traffic. The API can also start selected in-process services during its lifespan. Shutdown stops those services so the process does not leave active consumers or schedulers behind.

References: keep/…/config.py• L19-123 keep/…/api.py• L222-243 keep/…/api.py• L429-444 keep/…/arq_worker.py• L198-245

API composition

FastAPI application

The FastAPI application is the composition point for Keep's HTTP contract. It sets the service identity and version, adds a small root response, mounts route domains under stable prefixes, and gives the identity manager a chance to add auth-specific endpoints.

Route domains are grouped by product resource rather than by one large handler. The API route domains page describes those resources, their request and response models, and their business-logic boundaries.

References: keep/…/api.py• L246-341 keep/…/api.py• L291-333

Request boundary

Requests pass through a boundary that adds request IDs, tenant context, compression, cross-origin rules, logging, optional rate limits, and error handling. The logging middleware extracts a tenant from an auth token or API key when possible. The rest of the request can then use that context for logs and error responses.

The boundary returns a trace ID with an unexpected server error. This gives a client a value that an engineer can use to connect the failed request with server logs and traces. Rate limiting is opt-in and uses the configured request address as its key.

References: keep/…/api.py• L279-289 keep/…/api.py• L343-369 keep/…/middlewares.py• L19-69 keep/…/limiter.py• L10-17

Route interface

The route interface covers product resources such as alerts, incidents, providers, workflows, settings, authentication, health, and metrics. The composition layer assigns each route group a URL prefix and API tag. The workflow domain also gives clients a tenant-scoped interface to manage definitions, start runs, inspect versions and executions, and manage workflow secrets.

The route group owns the details of its resource contract; this page only describes how the groups enter the service. The API route domains page maps those contracts and their business-logic boundaries.

References: keep/…/api.py• L291-333 keep/…/workflows.py• L77-116 keep/…/workflows.py• L357-451 keep/…/workflows.py• L977-1145 keep/…/workflows.py• L1207-1323

Lifecycle management

Startup sequence

Startup prepares shared state before the API accepts normal work. The Gunicorn start hook runs database migrations, loads provider and tenant configuration, creates the single-tenant base when the selected auth mode needs it, and provisions configured providers, workflows, dashboards, deduplication rules, and mapping rules when resource provisioning is enabled. It can also create an ngrok tunnel and use its public URL as the API URL.

The server settings define the bind address and API worker count before the workers start. The worker count must be a positive integer. The start hook then performs the shared preparation before forked workers handle traffic. Each worker restores its logging setup after the fork so it does not reuse the parent process's handlers.

The FastAPI lifespan starts enabled schedulers, consumers, topology processing, and maintenance work for each API worker. The scheduler and consumer start independently. If one fails, the service records the failure and continues its startup path. This makes the API available in some partial-start cases, so operators must check the related logs and dependency state rather than rely on process start alone.

References: keep/…/config.py• L19-123 keep/…/db_on_start.py• L171-189 keep/…/api.py• L120-190

Shutdown sequence

Shutdown stops the workflow scheduler and event consumer. The ARQ worker closes its worker resources and waits for its event thread pool to finish. These paths are separate because the API process and queue worker have different lifecycles.

References: keep/…/api.py• L193-219 keep/…/arq_worker.py• L125-140 keep/…/arq_worker.py• L243-245

Background processing

ARQ worker system

ARQ is the queue worker system used for work outside the request path. Redis holds jobs and queue state. Worker task pools select which classes of work a worker accepts, with named queues for basic processing, workflows, and maintenance. The shared Redis settings support direct Redis and Redis Sentinel so the API's enqueue path and the worker's consume path use the same connection model.

The asynchronous jobs and event processing page traces queued tasks, subscribers, schedules, and retry behavior in more detail.

References: keep/…/arq_worker.py• L32-67 keep/…/arq_worker.py• L150-195 keep/…/redis_settings.py• L13-71 keep/…/consts.py• L36-52

Event processing

An event job carries tenant, provider, trace, and event data from intake to the processing task. The worker runs the processing function in a dedicated thread pool, then the task normalizes the event and connects it to persistence, incident and workflow effects, and client notifications. Generic events and already parsed alerts both pass through the custom deduplication path when it is enabled; events without a provider type use the keep provider rule. Failures are logged and queued runs request ARQ retries when the task has worker context.

This path is the main bridge between the API runtime and alert lifecycle behavior. It preserves the tenant and trace context so a job can be related back to the request or provider that created it. The database lookup applies the custom deduplication setting for all callers, which keeps the task and other event paths consistent.

Event handling also applies alert enrichment before and after alert processing. Extraction rules derive fields from event data, while mapping rules add data from configured sources such as topology or tabular mappings. The enrichment service writes the result to alert state and records the rule outcome with event logs, unless enrichment is disabled by configuration. This gives downstream incident and workflow logic one enriched alert view.

References: keep/…/arq_worker.py• L69-121 keep/…/process_event_task.py• L661-861 keep/…/enrichments_bl.py• L91-185 keep/…/enrichments_bl.py• L299-340 keep/…/enrichments_bl.py• L754-832 keep/…/db.py• L105-107 keep/…/db.py• L2589-2604

Periodic work

Periodic work covers workflow scheduling and maintenance checks. The watcher recovers maintenance-window state and expires dismissed alerts. With Redis it uses a Redis lock so only one run proceeds. Without Redis it uses a local file lock and sleeps between runs, which limits coordination to processes that share the same host.

The separate server-jobs process waits for the API to respond before it launches demo-mode and uptime-reporting threads. It must run beside the server rather than inside the API process.

References: keep/…/api.py• L164-188 keep/…/arq_worker.py• L150-162 keep/…/process_watcher_task.py• L13-66 keep/server_jobs_bg.py• L12-47

Configuration model

Environment settings

Configuration comes from the environment and, when present, the repository .env file. Settings choose the server bind address, port, worker count, concurrency limit, authentication mode, Redis use, service switches, metrics, tracing, logging, and resource provisioning. The central config object gives API modules one way to read these values, while the Gunicorn start settings control the bind address, worker count, and whether initial resources are provisioned.

The most important settings are grouped by effect:

  • Process shape: bind address, host, port, API worker count, and request concurrency.
  • Service switches: scheduler, consumer, topology processor, watcher, maintenance windows, enrichment processing, and debug modes.
  • Queue runtime: Redis connection mode, queue task pool, job result retention, and job expiry.
  • Telemetry: application metrics, OpenTelemetry, log level, log format, and optional log file.
  • Initial state: database migration and resource provisioning controls.
  • Development access: optional ngrok tunneling and the public API URL.

The configured worker count must be at least one. Gunicorn command arguments and explicit command-line flags can override the default bind value, while environment settings provide the normal deployment defaults.

References: keep/…/config.py• L1-11 keep/…/api.py• L79-90 keep/…/config.py• L19-27 keep/…/config.py• L31-50 keep/…/config.py• L52-123 keep/…/arq_worker.py• L53-67 keep/…/arq_worker.py• L179-194 keep/…/enrichments_bl.py• L91-105

Database preparation

The server-start hook owns migrations and initial installation setup before worker processes are forked. It loads provider and tenant state early, creates the required single-tenant base for supported auth modes, and provisions the configured product resources. This keeps database engines and connections from being shared across forked processes.

API workers create their own sessions after startup. The shared database layer provides the session boundary used by API and worker code. It instruments the engine for SQL traces and opens short-lived sessions for request or job work. Event processing uses that boundary to save alerts and related state before it sends downstream workflow and client updates.

References: keep/…/config.py• L52-92 keep/…/db_on_start.py• L1-14 keep/…/db_on_start.py• L171-189 keep/…/db.py• L89-95 keep/…/db.py• L136-158

Observability

Request signals

Observability means the signals used to see service health and behavior. Each request can carry a request ID, tenant ID, and trace ID. FastAPI, outbound requests, and logs can be instrumented with OpenTelemetry. The API also exposes Prometheus-style metrics through a protected metrics route and a processing metrics route.

The customer-facing metrics describe tenant alert, incident, and workflow totals. They are not a measure of API pod health. The processing endpoint serves internal multiprocess metrics and is protected unless no-auth metrics are explicitly enabled.

References: keep/…/observability.py• L40-115 keep/…/metrics.py• L27-68 keep/…/api.py• L361-369

Log context

Logs are emitted to standard output in structured form by default, with an optional rotating file. Request logs carry tenant and status context. Workflow and provider execution logs can also be stored in the database when their execution context is present. Worker type and OpenTelemetry fields help separate API and ARQ activity in shared log streams. Worker startup reinitializes the logging handlers after process fork so each worker writes through its own logging setup.

References: keep/…/logging.py• L24-29 keep/…/logging.py• L109-237 keep/…/logging.py• L325-384 keep/…/logging.py• L518-545 keep/…/config.py• L27-28 keep/…/config.py• L115-123

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep route prefixes and API tags aligned between get_app and the route-domain contract. A prefix change can break UI clients and external integrations without changing a route handler.
  • Keep workflow route permissions aligned with the operation exposed by each endpoint. A mismatch between read, write, execute, and secret access can deny valid calls or expose workflow data.
  • Keep ARQ queue names and task-pool selection aligned between enqueue sites, WorkerSettings, and deployed worker processes. A valid job can remain unconsumed when the worker listens to another pool or queue.
  • Keep Redis connection settings identical for the API enqueue path and ARQ workers. Sentinel and direct-Redis modes must describe the same backend.
  • Keep lifespan flags aligned with deployment roles. Starting a consumer or scheduler in every API worker can duplicate work.
  • Keep server bind and worker-count settings valid for the Gunicorn process. A worker count below one prevents startup, while a bind override can change the address used by the service.
  • Keep trace and tenant context fields aligned across middleware, exception responses, logs, and queued event arguments so one operation remains searchable end to end.
  • Keep custom deduplication enablement and provider identity aligned between event inputs and the database rule lookup. Inputs without a provider type must resolve to the keep provider rule.
  • Keep enrichment enablement aligned with the rule sources and with downstream alert consumers. Disabling enrichment changes the fields and rule-event records available to incident and workflow processing.
  • Keep metrics authentication and scrape configuration aligned. The customer-facing metrics route and internal processing metrics route have different purposes and access rules.
  • Keep resource provisioning inputs aligned with the resources expected by a new installation. Disabling provisioning or changing its environment inputs can leave providers, workflows, dashboards, deduplication rules, or mapping rules absent.
  • Keep the public API URL aligned with any ngrok tunnel settings. A tunnel changes the URL used by downstream callbacks and clients.

Important failure modes

TriggerConsequenceGuard
Redis is unavailable while a Redis-backed watcher or queue worker startsJobs cannot be enqueued or consumed. The worker retries its connection after a delay.Check Redis reachability and the selected direct or Sentinel settings.
A worker listens to a queue or task pool that does not match the enqueued jobThe job stays pending even though the API accepted it.Deploy matching KEEP_ARQ_TASK_POOL and queue settings.
KEEP_API_WORKERS is zero or negativeGunicorn configuration fails before the service can start.Set KEEP_API_WORKERS to a positive integer.
A workflow request uses a permission scope that does not match its operationThe client receives an authorization failure before the workflow action runs.Keep route scopes aligned with workflow read, write, execute, and secret operations.
Custom deduplication is disabled or a rule is not configured for the resolved providerMatching incoming alerts bypass the custom rule and may use only the remaining deduplication behavior.Check KEEP_CUSTOM_DEDUPLICATION_ENABLED and configure the rule for the provider and tenant.
KEEP_ENRICHMENT_DISABLED is enabled when alert fields depend on extraction or mapping rulesAlerts reach downstream processing without the derived fields and enrichment event records.Confirm the setting and the required tenant rules before enabling event processing.
Scheduler, consumer, or topology startup failsThe API can still finish startup while that background capability is absent.Check startup logs for each service and validate its dependency separately.
The simple health endpoint returns successfully while a dependency is downA load balancer can see HTTP success without proving database, Redis, or consumer readiness.Use dependency checks and runtime metrics in addition to /healthcheck.
More than one non-Redis watcher runs on hosts without a shared /tmp lockMaintenance work can run more than once.Use Redis for cross-process coordination or deploy one watcher role.
OpenTelemetry is enabled with an unsupported exporter endpoint schemeObservability setup raises a configuration error instead of creating the intended exporter.Use the supported HTTP or grpc endpoint form and verify exporter settings at startup.
Resource provisioning is disabled or its inputs are incomplete during startupA new installation can start without the providers, workflows, dashboards, deduplication rules, or mapping rules that its product setup expects.Keep PROVISION_RESOURCES and its source settings enabled and complete when startup provisioning is required.
An ngrok tunnel is enabled with invalid tunnel settingsStartup cannot establish the public endpoint or sets an unusable API URL.Use a valid NGROK_AUTH_TOKEN and optional NGROK_DOMAIN only when the tunnel is required.

Key files

FileWhy to read it
keep/…/api.pyShows FastAPI assembly, middleware, route mounting, lifespan startup, shutdown, and server launch.
keep/…/workflows.pyIllustrates a tenant-scoped product route domain that manages workflow definitions, runs, versions, execution views, and secrets.
keep/…/middlewares.pyDefines the request-level tenant context and request timing logs.
keep/…/config.pyShows Gunicorn defaults, pre-worker database setup, tenant initialization, resource provisioning, optional public tunneling, and worker logging setup.
keep/…/db.pyDefines the shared database session boundary and event-related rule lookup behavior.
keep/…/arq_worker.pyDefines worker task selection, queue behavior, lifecycle hooks, and retry-on-connection behavior.
keep/…/redis_settings.pyDefines the shared direct-Redis and Redis Sentinel connection model.
keep/…/process_event_task.pyShows the main event job boundary and its downstream effects.
keep/…/enrichments_bl.pyShows how event and mapping rules add alert data and record enrichment outcomes.
keep/…/process_watcher_task.pyShows maintenance scheduling and cross-process locking.
keep/…/observability.pyDefines trace, metric, request, and log instrumentation.
keep/…/logging.pyDefines structured logs and persistence of workflow and provider execution logs.
keep/…/healthcheck.pyDefines the basic process health endpoint.
keep/…/metrics.pyDefines customer-facing and processing metric endpoints.
keep/server_jobs_bg.pyShows the separate process for long-running server jobs.