Skip to content

API configuration, access and rate limiting

The API’s controls act at different points in a request. Nginx decides whether traffic reaches PHP. The deployment runtime reads its token, database location, catalogue and session lifetime. The application then validates the JSON and performs a session operation. Knowing which component made a decision tells you which setting to change and what your application can do with the response.

This guide covers the supplied Nginx and PHP-FPM deployment, followed by the different scope of the reusable application middleware. It reuses the isolated service from Docker deployment: a loopback HTTP entry point, a private token and a SQLite volume. The examples below inspect its shipped demo-flow catalogue entry without creating a session. An existing service with another catalogue can use one of its own graph codes.

Put each setting in the component that reads it

Section titled “Put each setting in the component that reads it”

RuntimeConfig::fromEnvironment() reads four values inside the API container. Compose supplies the fixed database and catalogue paths and maps its host-side settings into that environment:

Setting Where it applies Operational consequence
EXECKERNEL_SQLITE_PATH PHP runtime; /var/lib/execkernel/sessions.sqlite in the supplied Compose file. Keep its parent directory on persistent, writable storage.
EXECKERNEL_GRAPH_DIR PHP runtime; /app/resources/graphs in the supplied Compose file. This directory is the trusted catalogue available to requests.
EXECKERNEL_SESSION_TTL_SECONDS PHP session store; positive integer, default 86400. An execution can expire based on its saved activity timestamps.
EXECKERNEL_API_TOKEN_FILE PHP reads /run/secrets/api_token; Compose’s setting selects the host file mounted there. The runtime user must be able to read a valid token.
EXECKERNEL_BIND, EXECKERNEL_PORT Compose’s host port mapping. They change the HTTP listener’s exposure, not a PHP route.
EXECKERNEL_API_IMAGE, EXECKERNEL_WEB_IMAGE Compose image selection. Pin the artifacts that will actually run.

The first two paths are explicitly fixed by the supplied Compose file. Merely exporting a same-named host variable does not replace them: use a reviewed Compose override if you need different paths. The session lifetime and host token-file path are interpolated from the Compose environment file.

The deployment token must contain 32–256 characters from A–Z, a–z, 0–9, _ or -, after surrounding whitespace is trimmed. The deployment guide generates 32 random bytes encoded as 64 hexadecimal characters. There is one service credential; it does not assign user roles, tenants or business permissions. Your backend must decide which person may access each session before forwarding the operation.

Keep the token outside browser code, request URLs and logs. A session identifier selects an execution and does not replace the Bearer credential. When rotating the token, prepare a new private host file, update EXECKERNEL_API_TOKEN_FILE in the deployment environment file and recreate the services so the new secret is mounted and startup validation runs:

Terminal window
ekcompose up -d --no-build --pull never --force-recreate --wait

Here ekcompose is the project-specific Compose command defined in Docker deployment. Update the backend’s credential and the rehearsal’s private curl header file as part of the same rotation. The deployment accepts a single configured token, so plan the handover accordingly.

The catalogue is a directory of operator-supplied JSON graph definitions. It loads *.json files directly in the configured directory. A request sends a graph code or numeric ID; it cannot select a filesystem path or upload a replacement graph. Each entry needs a unique graph_code and a unique positive integer graph_id. Files must be regular JSON files; the catalogue loader rejects symbolic links, duplicate identities, invalid definitions and an empty catalogue.

To use a reviewed catalogue directory with the existing rehearsal, add the repository’s read-only mount override. Replace the path below with the actual directory containing your JSON files:

Terminal window
export EXECKERNEL_GRAPH_HOST_DIR=/absolute/path/to/trusted-graphs
docker compose --env-file "$OPS_DIR/deployment.env" \
-p execkernel-production-check \
-f compose.yaml -f deploy/compose.graphs.yaml \
up -d --no-build --pull never --wait

Keep the same two Compose files in later operations on that deployment. The runtime user needs read access to the directory and files. Validate a changed catalogue in a separate instance before switching it: a malformed entry can fail startup or /healthz, even when a request would have selected another graph.

Saved sessions still need compatible definitions. This reuses the distinction in Graph identity and versioning: a graph identity ties the saved execution to a definition, and changing its meaning can make the saved position unusable. Preserve definitions used by active sessions or carry out an explicit, verified migration.

Distinguish public operations from internal resources

Section titled “Distinguish public operations from internal resources”

In the supplied deployment, GET /healthz is accessible without the service token. API operations under /execkernel/ require exactly one Authorization: Bearer … header with the configured token. Missing, malformed or incorrect credentials receive HTTP 401, code EK-API-003 and a WWW-Authenticate: Bearer realm="ExecKernel" header.

/internal/metrics is unavailable through this deployment. Nginx does not forward /internal/, and DeploymentAccessMiddleware also returns 404 for that prefix, even with a valid token. Passing the deployment token does not enable an internal metrics endpoint.

The reusable createApp() bootstrap is a different integration boundary. It registers /internal/metrics but does not install DeploymentAccessMiddleware or an internal credential check. If your application exposes that route, supply its authentication and restrict its network access yourself. There is no built-in separate metrics password to configure. Metrics and operational monitoring explains the registry’s lifetime and what its counters mean.

Choose the request limit for the actual host

Section titled “Choose the request limit for the actual host”

In the supplied deployment Nginx limits requests by connecting IP before PHP validates the service token. A custom application may retain a session limiter object, whose counters disappear when that object is replaced. These are separate scopes.

The supplied runtime explicitly disables the application’s session rate limiter. Its operational ingress control is the Nginx configuration:

limit_req_zone $binary_remote_addr zone=execkernel_ip:10m rate=10r/s;
location ^~ /execkernel/ {
limit_req zone=execkernel_ip burst=40 nodelay;
limit_req_status 429;
# The complete repository configuration forwards this location to PHP-FPM.
}

The zone is shared within that Nginx instance and uses the connecting IP address. 10r/s sets the sustained admission rate; burst=40 nodelay allows a bounded excess burst without delaying those admitted requests. This is not a fixed allowance of ten requests in each wall-clock second. All /execkernel/ operations share that IP bucket, including inspection, starts, choices and requests that would later fail authentication.

Behind another reverse proxy, the connecting IP may be the proxy’s address. Configure trusted client-address handling in your ingress if you need a different key; the supplied file does not use arbitrary forwarded headers as client identity. Multiple independent Nginx instances do not share this zone.

Control Key and coverage Where its accounting lives
Supplied Nginx ingress Connecting IP; all /execkernel/ requests. That Nginx instance’s shared zone.
ExecKernelRateLimitMiddleware Trimmed session_id; next and resume by default. One retained middleware object’s PHP memory.
Application’s business authorization The user and execution identified by your application. Your application; the service token does not implement it.

For a custom host that retains its application objects between calls, createApp() accepts rateLimitRequests and rateLimitWindowSeconds; defaults are 30 requests in a 60-second window. rateLimitTargetEndpoints or shouldApplyRateLimit can select other coverage. The middleware needs a valid JSON object containing a nonempty string session_id to select a bucket. Rejected requests without a usable session identity are left to the normal validation path.

These parameters do not turn PHP memory into a deployment-wide counter. Standard FPM request handling builds a new app for each request; reusing a worker process does not preserve that object’s counters. Restarting or replacing a retained object also resets its accounting. This is why deploy/runtime.php passes a callback that disables this middleware and relies on Nginx for ingress limiting.

The middleware scope example isolates that distinction. It sets a one-request limit, sends the same synthetic session identity twice through one object, then once through a new object. Its downstream handler only returns 200; it does not execute a graph or check a token. The result is:

{"same_object":[200,429],"new_object":200}

The first object’s second call receives 429; a replacement starts with no recorded calls. To run the complete example with the API project’s Composer dependencies available, save it in the project root and run php api-middleware-scope.php. This demonstrates object lifetime, not a distributed limiter.

Recognize admitted, denied and limited requests

Section titled “Recognize admitted, denied and limited requests”

The deployment rehearsal keeps OPS_DIR, EXECKERNEL_BASE_URL and a private auth.header file. With those values, inspect the known catalogue entry:

Terminal window
curl --include --silent --show-error \
"$EXECKERNEL_BASE_URL/execkernel/graph/inspect" \
--header "@$OPS_DIR/auth.header" \
--header 'Content-Type: application/json' \
--data '{"flow":"demo-flow"}'

HTTP 200 and a graph description containing nodes 1 and 2 and edge 10 show that ingress admitted the request, the token passed and the API loaded the requested graph. A selected excerpt is:

{
"nodes": [{"id":1,"isTerminal":false},{"id":2,"isTerminal":true}],
"edges": [{"id":10,"fromNode":1,"toNode":2}]
}

Repeat the same request without the authorization header:

Terminal window
curl --include --silent --show-error \
"$EXECKERNEL_BASE_URL/execkernel/graph/inspect" \
--header 'Content-Type: application/json' \
--data '{"flow":"demo-flow"}'

The deployment access middleware returns HTTP 401. Its JSON body has this shape; the diagnostic message is shown as returned:

{
"error": {
"code": "EK-API-003",
"message": "No autorizado.",
"details": {"http":401,"trace_id":"<request-trace>"}
}
}

To observe ingress limiting, run the bounded rate probe only against the separate rehearsal. It accepts a literal loopback address, sends 80 graph-inspection requests with at most 16 concurrent workers and does not create sessions:

Terminal window
curl --fail --location --silent --show-error \
https://docs.execkernel.org/examples/production/api-rate-probe.py \
--output "$OPS_DIR/api-rate-probe.py"
python3 "$OPS_DIR/api-rate-probe.py" \
--base-url "$EXECKERNEL_BASE_URL" \
--token-file "$OPS_DIR/api-token"

The program reports counts of HTTP 200 and 429 and one limited response. Counts depend on timing; the check is that both admission and limiting occur. Nginx’s response is:

{
"error": {
"code": "EK-RATE-429",
"message": "Ingress rate limit exceeded.",
"details": {"http":429,"trace_id":"<request-trace>"}
}
}

That rejection happens before PHP. In contrast, the reusable session middleware uses the same error code with "Rate limit exceeded for session." and adds session_id, window_seconds and max_requests to details. Use the deployment topology and response details together to identify the responsible layer; the error code alone does not distinguish them.

Successful API responses and these error responses carry X-Trace-Id; retain it when reporting a particular request failure. The supplied Nginx security headers also include Cache-Control: no-store and X-Content-Type-Options: nosniff. These response controls do not replace the token check.

Neither implementation supplies a Retry-After header. Your application should slow down after 429, surface credential failures separately and avoid automatically repeating state-changing requests whose outcome is unknown. The client error guide explains that recovery decision: use a retained session identifier to read the confirmed state before choosing another write.

Keep size and JSON validation separate from rate control

Section titled “Keep size and JSON validation separate from rate control”

Nginx’s client_max_body_size 128k rejects oversized bodies with HTTP 413 and EK-INPUT-400. Its limit applies before the PHP controller parses JSON. The PHP image also sets post_max_size=128K; neither setting is an environment option of RuntimeConfig.

Once a request reaches the API, JsonRequest requires a JSON object and rejects duplicate object fields, unsupported numeric values and malformed JSON. Session context is a flat object with string keys and scalar values, as developed in HTTP API integration: send the facts the graph needs rather than nested application records. Input validation failures receive HTTP 400.

Changing a request-size limit requires reviewing the Nginx/PHP configuration; changing JSON or context shape is not a deployment setting. Keep these decisions distinct from request frequency so increasing a traffic allowance does not disguise invalid input.