---
title: "Sleep an on-demand environment"
method: POST
path: "/projects/{project_id}/environments/{env_id}/sleep"
tags: ["Environments"]
---

# Sleep an on-demand environment

`POST /projects/{project_id}/environments/{env_id}/sleep`

## Request

- Base URL: `/api` (relative, and the document was published on a file host, not at the API’s origin)
- URL: `/api/projects/{project_id}/environments/{env_id}/sleep`
- Auth: HTTP bearer

Manually put an on-demand environment to sleep. Stops containers and sets
`sleeping = true`. If no OnDemandWaker is available, falls back to DB flag only.

## Path parameters

- `project_id` integer, required
- `env_id` integer, required

## Response `200`

Environment put to sleep

- EnvironmentResponse
  - `attack_mode` boolean, nullable: Per-environment CAPTCHA attack-mode override. `null` means inherit the project-level `attack_mode`; `true`/`false` explicitly enable/disable the challenge for this environment. Always serialized (NOT skipped) so the UI can distinguish `null` from `false`.
  - `branch` string, nullable
  - `created_at` string, date-time, required
  - `current_deployment_id` integer, nullable
  - `deployment_config` DeploymentConfig, nullable: Deployment configuration shared between projects and environments This configuration can be set at the project level (as defaults) and overridden at the environment level for specific deployments. Note: Environment variables are managed separately and are not part of this config.
    - `antiAffinity` boolean: Anti-affinity: spread replicas across different nodes. When enabled, the scheduler avoids placing two replicas of the same environment on the same node. If there are fewer eligible nodes than replicas, remaining replicas wrap around (best-effort spreading). Defaults to `true` — replicas spread by default.
    - `automaticDeploy` boolean, nullable: Enable automatic deployments on git push. `None` = inherit from project config; `Some(true/false)` = explicit override. Stored as JSONB so absent key → `None` (inherit), never silently defaults to false.
    - `buildLocation` 'control_plane' | 'node' | 'ci', nullable: Where a source deployment's image is built. The control plane is the default and the historical behaviour. `Node` moves the build — the most CPU- and memory-hungry step of a deployment — onto a worker node so it stops competing with the proxy, the database and running workloads on the control plane. A node labelled `temps.sh/role=builder` is preferred; otherwise the node the deployment is placed on builds it. `Node` is a preference, not a requirement: when no worker can take the build (none joined, none of the right architecture, or a multi-architecture build) the build runs on the control plane and the build log says why. A static site may build on a worker of any architecture, since its output is read from that node and never runs.
    - `containerExecEnabled` boolean: Enable container exec/shell access (disabled by default for security)
    - `cpuLimit` integer, nullable: CPU limit in microcores, where 1_000_000 = 1 full CPU core (e.g., 2_000_000 = 2 CPUs). NOT millicores. `None` = uncapped.
    - `cpuRequest` integer, nullable: CPU request in microcores, where 1_000_000 = 1 full CPU core (e.g., 100_000 = 0.1 CPU, 500_000 = 0.5 CPU, 2_000_000 = 2 CPUs). NOT millicores — the deployer formats this as `{n}u` and converts `n / 1_000_000` cores into Docker nano_cpus.
    - `crossArchitectureBuilds` boolean, nullable: Build one image per architecture the eligible nodes run. `None`/`false` (the default) builds exactly once, on the control plane's native platform — byte-for-byte the behaviour of a single-architecture cluster. When enabled and the nodes this deployment could land on span more than one architecture, the build job produces one image per architecture; the non-native ones go through the daemon's `platform` option, which requires QEMU binfmt handlers registered on the control plane. **Opt-in on purpose.** Cross-architecture builds are emulated and substantially slower, and deriving them from cluster topology would mean a single node joining silently changes build behaviour for every deployment in the cluster. It also keeps the decision on operator config rather than on a value each node reports about itself. `Option<bool>` so an environment inherits the project's setting (`None`) or overrides it, matching `automatic_deploy`.
    - `exposedPort` integer, nullable: Port exposed by the container If not specified, will be auto-detected from Docker image or default to 3000
    - `health` HealthCheckConfig, nullable: Health check configuration
      - `command` string[]: Argument vector executed directly inside the container (no implicit shell).
      - `interval` integer: Interval between health checks in seconds (default: 30)
      - `path` string: HTTP path for health checks
      - `retries` integer: Number of consecutive failures before marking unhealthy (default: 3)
      - `stable_for` integer: Continuous running window for a process probe, in seconds.
      - `status` integer: Expected HTTP status code (default: 200)
      - `timeout` integer: Timeout for health check requests in seconds (default: 5)
      - `type` string, nullable: Probe kind. Unset selects HTTP for a declared port, process otherwise.
    - `healthCheckTimeoutSeconds` integer, nullable: How long, in seconds, a new container may take to start and pass its readiness check before the deployment fails. Covers apps that boot slowly (migrations, JIT warm-up, large model loads). `None` = the platform default ([`DEFAULT_HEALTH_CHECK_TIMEOUT_SECONDS`]); valid overrides are [`MIN_HEALTH_CHECK_TIMEOUT_SECONDS`]..= [`MAX_HEALTH_CHECK_TIMEOUT_SECONDS`]. Environments inherit the project value and may override it.
    - `idleTimeoutSeconds` integer: Seconds of inactivity before containers are stopped in on-demand mode. Only used when `on_demand` is true. Min: 60, Max: 86400 (24h). Default: 300 (5 minutes).
    - `loadBalancing` LoadBalancingConfig, nullable
      - `healthCheck` ActiveHealthCheck
        - `enabled` boolean
        - `healthyThreshold` integer
        - `intervalSeconds` integer
        - `path` string, nullable: Origin-relative path; defaults to deployment readiness path, then `/`.
        - `timeoutSeconds` integer
        - `unhealthyThreshold` integer
      - `maxInFlightPerReplica` integer, nullable
      - `preferredNodeIds` integer[]: Ordered node preference; zero denotes the local control plane.
      - `strategy` 'round_robin' | 'preferred_nodes': Replica selection policy. Absent configuration preserves round robin.
    - `maxConcurrentConnections` integer, nullable: Override for the proxy's cap on concurrent in-flight requests to this project/environment's upstream, independent of the timeout overrides above. `None` = inherit the global `connection_limits.default_max_concurrent_connections`. `Some(0)` explicitly forces "unlimited" for this project/environment, overriding a nonzero global default. `Some(n)` for `n > 0` sets an explicit cap — there is no global ceiling clamp here (unlike the timeout settings): an operator who has explicitly set a per-project value has made a deliberate choice and the platform should respect it.
    - `memoryLimit` integer, nullable: Memory limit in megabytes. Three-state semantics: - `None` → inherit the parent layer (env inherits project, project inherits the seeded default); used by the settings UI's "Use default". - `Some(0)` → explicit **uncapped**: stop inheriting and run with no memory limit. This is the deliberate escape hatch for dedicated workloads, distinct from `None`. - `Some(n)` → hard cap of `n` MB. `merge`/resolution keep `Some(0)` as a present value (it wins precedence over a parent cap), and the deployer collapses it to "no limit" before talking to Docker.
    - `memoryRequest` integer, nullable: Memory request in megabytes (e.g., 128 = 128MB)
    - `onDemand` boolean: Enable on-demand mode (scale-to-zero). When enabled, containers are stopped after `idle_timeout_seconds` of no traffic and automatically started when a new request arrives.
    - `performanceMetricsEnabled` boolean: Enable performance metrics collection (speed insights)
    - `replicas` integer: Number of replicas/instances to run Defaults to 1 replica
    - `requestTimeoutSeconds` integer, nullable: Override for the proxy's upstream timeout on regular (non-streaming) HTTP requests to this project/environment, in seconds. `None` = inherit the global `request_timeouts.default_http_timeout_seconds` (which itself defaults to "no timeout"). `Some(0)` explicitly forces "no timeout" for this project/environment, overriding a nonzero global default. `Some(n)` for `n > 0` sets an explicit timeout, always clamped to the global hard ceiling (`request_timeouts.max_request_timeout_seconds`) at resolution time.
    - `security` SecurityConfig, nullable: Security configuration for projects and environments This configuration can be set at three levels: 1. Global (in settings table) - applies to all projects 2. Project level - overrides global settings for specific project 3. Environment level - overrides project settings for specific environment The inheritance chain: Environment > Project > Global
      - `attackMode` string, nullable: Attack mode configuration (future: "off", "challenge", "block") Placeholder for DDoS protection, bot detection, etc.
      - `challengeConfig` ChallengeConfig, nullable: Challenge configuration (future feature) For CAPTCHA, JS challenges, proof-of-work, etc.
        - `challengeType` string, required: Challenge type: "captcha", "js_challenge", "proof_of_work"
        - `difficulty` integer, required: Challenge difficulty level (1-10)
        - `protectedPaths` string[]: Paths that require challenges
      - `enabled` boolean, nullable: Enable/disable security features at this level If None, inherits from parent level
      - `geoRestrictions` GeoRestrictionsConfig, nullable: Geographic restrictions configuration (future feature)
        - `allowedCountries` string[]: Allow traffic only from specific countries
        - `blockedCountries` string[]: Block traffic from specific countries (ISO 3166-1 alpha-2 codes)
      - `headers` SecurityHeadersConfig, nullable: Security headers configuration (subset of global SecurityHeadersSettings)
        - `contentSecurityPolicy` string, nullable: Custom CSP (only used if preset is "custom")
        - `preset` string, nullable: Use a preset: "strict", "moderate", "permissive", "disabled", "custom"
        - `referrerPolicy` string, nullable: Referrer-Policy override
        - `strictTransportSecurity` string, nullable: HSTS override
        - `xFrameOptions` string, nullable: X-Frame-Options override
      - `passwordProtection` PasswordProtectionConfig, nullable: Password protection configuration When enabled, the proxy shows an HTML password form before allowing access. After the user enters the correct password, an HMAC-signed cookie is set so subsequent requests pass through without re-entering the password.
        - `enabled` boolean, required: Whether password protection is enabled
        - `passwordHash` string, required: The bcrypt-hashed password (never stored or returned in plaintext)
      - `rateLimiting` RateLimitConfig, nullable: Rate limiting configuration (subset of global RateLimitSettings)
        - `blacklistIps` string[]: Blacklist specific IPs for this project/environment
        - `maxRequestsPerHour` integer, nullable: Override rate limit per hour
        - `maxRequestsPerMinute` integer, nullable: Override rate limit per minute
        - `whitelistIps` string[]: Whitelist specific IPs for this project/environment
    - `sessionRecordingEnabled` boolean: Enable session recording for analytics
    - `sseIdleTimeoutSeconds` integer, nullable: Override for the proxy's idle timeout on Server-Sent Events streams to this project/environment, in seconds. `None` = inherit the global `request_timeouts.default_sse_idle_timeout_seconds`. `Some(0)` explicitly forces "no timeout". `Some(n)` for `n > 0` is clamped to the global hard ceiling at resolution time.
    - `stopTimeoutSeconds` integer, nullable: How long, in seconds, a superseded deployment's containers get to finish in-flight work after SIGTERM before they are killed, once a new deployment has gone live. Raise it for long requests (uploads, exports, streaming responses, WebSockets). An override is 1 to 3600 seconds. Absent on a project means the platform default of 10 seconds; absent on an environment means it inherits the project's value, else the platform default.
    - `targetLabels` unknown
    - `targetNodes` integer[], nullable: Optional list of node IDs to deploy to. When set, replicas are distributed only across these nodes (round-robin). When None, the scheduler distributes across all active nodes (or deploys locally if no nodes exist).
    - `wakeTimeoutSeconds` integer: Max seconds to wait for containers to start when waking from on-demand sleep. Requests return 503 if exceeded. Default: 30.
    - `websocketIdleTimeoutSeconds` integer, nullable: Override for the proxy's idle timeout on WebSocket connections to this project/environment, in seconds. `None` = inherit the global `request_timeouts.default_websocket_idle_timeout_seconds`. `Some(0)` explicitly forces "no timeout". `Some(n)` for `n > 0` is clamped to the global hard ceiling at resolution time.
  - `estimated_sleep_at` string, date-time, nullable: Estimated time (ISO 8601, UTC) when the environment will go to sleep based on last activity + idle timeout. NULL when sleeping or on-demand disabled.
  - `force_https` boolean, nullable: Per-environment HTTP→HTTPS redirect override. `null` means inherit the proxy default (redirect only when the host has an active TLS certificate); `true` always redirects plain HTTP for this environment, `false` never does. Always serialized (NOT skipped) so the UI can distinguish `null` from `false`.
  - `id` integer, required
  - `is_preview` boolean, required: Indicates if this is a preview environment (auto-created per branch) For preview environments, 'branch' contains the feature branch name
  - `last_activity_at` string, date-time, nullable: Last proxied request time (ISO 8601, UTC) for on-demand environments. NULL when on-demand is disabled or no traffic has been received yet.
  - `main_url` string, required
  - `name` string, required
  - `placement_warning` string, nullable: Set when the settings can't be honoured as written: anti-affinity is on, but there are fewer eligible nodes than replicas, so some replicas will share a node. Deploys still go ahead. Reported when reading one environment and when saving its settings, not in lists.
  - `project_id` integer, required
  - `protected` boolean, required: When true, git pushes do NOT auto-deploy to this environment. Deployments must be promoted from another environment.
  - `shield_exempt_paths` string[], required: Paths Shield never challenges in this environment (ADR 066 D7): `/api/*` exempts everything under `/api/`, any other entry one exact path.
  - `shield_mode` 'off' | 'log' | 'selective' | 'attack', nullable, required: How an environment acts on verdicts (D1).
  - `sleeping` boolean, required: When true, the environment's containers are currently stopped due to inactivity (on-demand mode) and will start on the next request.
  - `slug` string, required
  - `subdomain` string, required: The host label stored for this environment (e.g. `myproject-production`). This is the prefix that is combined with the platform's preview domain at request time to produce `main_url`. Edit this via the rename-subdomain endpoint, not the full URL.
  - `updated_at` string, date-time, required

## Other responses

- `400`: On-demand not enabled for this environment
- `404`: Environment not found
- `429`: Too many state transitions, retry after cooldown
- `500`: Internal server error

## Changes

- **2026-11-26** `e1864d950604`: 4 breaking
  - the `created_at` response's property type changed from `integer` to `string`, and format from `int64` to `date-time` for status `200`
  - the `estimated_sleep_at` response's property type changed from `integer, null` to `string, null`, and format from `int64` to `date-time` for status `200`
  - the `last_activity_at` response's property type changed from `integer, null` to `string, null`, and format from `int64` to `date-time` for status `200`
  - the `updated_at` response's property type changed from `integer` to `string`, and format from `int64` to `date-time` for status `200`
- **2026-11-25** `480a86944327`: 1 info
  - the endpoint scheme security `bearer_auth` was added to the API
- **2026-11-16** `424e15926bbe`: 1 info
  - added the optional property `deployment_config/oneOf[#/components/schemas/DeploymentConfig]/loadBalancing` to the response with the `200` status
- **2026-11-06** `6ad6cfa11620`: 1 info
  - added the optional property `deployment_config/oneOf[#/components/schemas/DeploymentConfig]/stopTimeoutSeconds` to the response with the `200` status
- **2026-11-03** `0add2fdd114a`: 1 info
  - added the optional property `placement_warning` to the response with the `200` status

[Operation history](https://skmtc.dev/gotempsh/apis/temps/changes/projects/:project_id/environments/:env_id/sleep/post.md)

---

[API](https://skmtc.dev/gotempsh/apis/temps.md) - [All operations](https://skmtc.dev/gotempsh/apis/temps/llms.txt) - [OpenAPI document](https://skmtc.dev/gotempsh/apis/temps/revisions/3b040526eb43?raw)
