> ## Documentation Index
> Fetch the complete documentation index at: https://cosmo-docs.wundergraph.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Deployment

> Learn how to deploy and start the Router in Production.

## Run the Router

The router is a Go application provided as a self-contained Docker container. You can initiate the router by executing a single Docker command:

```bash theme={"system"}
docker run \
    --name cosmo-router \
    -e GRAPH_API_TOKEN=<router_api_token> \
    -e LISTEN_ADDR=0.0.0.0:3002 \
    -p 3002:3002 \
    ghcr.io/wundergraph/cosmo/router:latest
```

You can generate a token with the [`wgc router token create`](https://cosmo-docs.wundergraph.com/cli/router/token/create) CLI command.

## Health checks

By default, the health check endpoint is exposed at the path `/health`. The health check reports if the router is alive.

### Kubernetes

If you are on Kubernetes you can make use of our liveness and readiness checks. For convenience, we export both on `/health/live` and `/health/ready`:

```yaml theme={"system"}
containers:
  - name: router
    livenessProbe:
      httpGet:
        path: "/health/live"
        port: 3002
    readinessProbe:
      httpGet:
        path: "/health/ready"
        port: 3002
```

The liveness route returns `200` when the router is up. The readiness handler returns `200` only when the router is ready to serve requests.

#### Graceful shutdown

Before a Pod is terminated, a *SIGTERM* signal is sent to the Pod. Afterward, the Pod has 30 seconds to terminate itself (see [terminationGracePeriodSeconds](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination)). Ensure that the router-specific timeouts are set below this threshold or increase the termination period appropriately.

On a stop signal, the router shuts down in two phases, both within `SHUTDOWN_DELAY`:

1. **Drain** (up to `DRAIN_PERIOD`): the router keeps serving requests, but answers every response with `Connection: close` and reports `503` on the readiness endpoint. Clients that pool keep-alive connections, such as a proxy or load balancer in front of the router, retire each connection after its next response instead of reusing it. The drain ends as soon as all client connections are closed. WebSocket upgrades are not affected.
2. **Shutdown** (up to `GRACE_PERIOD`): the router stops accepting connections, waits for in-flight requests to finish, and cleans up its resources.

`DRAIN_PERIOD` defaults to `SHUTDOWN_DELAY - GRACE_PERIOD`, so the drain uses the part of the shutdown delay that the grace period leaves.

For example, the following configuration was tested and could serve as a good starting point:

**Router**

* `GRACE_PERIOD=20s`

* `SHUTDOWN_DELAY=30s`

`Pod`

* `terminationGracePeriodSeconds=60`

With that configuration, the router drains connections for up to 10 seconds and then has up to 20 seconds to finish in-flight requests, so it is gone within 30 seconds. Kubernetes will not terminate the container until the termination period of 60 seconds is over. Because the readiness endpoint no longer responds `200` and the container is in `TERMINATION` state, no new traffic is routed to the instance.

> [!NOTE]
>
> Without a drain, the router closes idle keep-alive connections immediately on shutdown. A client that sends a request on one of those connections at the same moment gets an `EOF`, and because GraphQL requests are `POST` requests, clients and proxies do not retry them. Set `DRAIN_PERIOD` above the idle connection timeout of any pooled client in front of the router so that every pooled connection is retired before the router shuts down. Set `DRAIN_PERIOD=0s` to disable the drain.

`GRACE_PERIOD` also applies when the router updates its schema. After all in-flight requests on the old schema have finished, it is the time the router has to clean up the old graph's resources.

> [!NOTE]
>
> For more information, we recommend the [Kubernetes Best Practice Terminating With Grace](https://cloud.google.com/blog/products/containers-kubernetes/kubernetes-best-practices-terminating-with-grace) article.

## Kubernetes & Container environments

To make the application reachable within the container network, you need to expose the router on `0.0.0.0` e.g `LISTEN_ADDR=0.0.0.0:3002.` This is also required when trying to access Prometheus metrics from outside the docker network. Use `PROMETHEUS_LISTEN_ADDR="0.0.0.0:8088"` to make the endpoint accessible.

## Logging

Structured logging, also known as JSON logging, is enabled by default and can be controlled using the `JSON_LOG` environment variable. For development, we recommend setting this off because the logs are more friendly rendered.

## Observability & Operations

The router exposes useful metrics about the process and memory. All metrics can be scraped from the Prometheus metrics endpoint. For more information please visit the dedicated [Metrics](https://cosmo-docs.wundergraph.com/router/metrics-and-monitoring.md) section.

### Tracing Sampling Rate

In scenarios with low traffic, a sampling rate of 1 (100%) is acceptable. However, for high-volume situations, we strongly recommend using a lower sampling rate. For instance, in a project experiencing 60 requests per second, a sampling rate of 0.1 (10% 6 req/s) is sufficient to generate valuable insights.

If you export to Cosmo Cloud, which is enabled by default, your account's trace sampling limit caps the `sampling_rate` of the Cosmo Cloud exporter. The limit also applies to traces sampled upstream with `parent_based_sampler`. The exporter's effective rate is the lower of the global and its own `sampling_rate`. If it exceeds the limit, the router logs a warning. Other exporters keep their configured rates. Please consider upgrading your plan or contact us for custom limits.

> [!NOTE]
>
> Ensure that your subgraphs use parent-based sampling to inherit the sampling rate. For more information see [OTEL instrumentation on Subgraphs](https://cosmo-docs.wundergraph.com/tutorial/otel-instrumentation-on-subgraphs.md).

## Configuration recommendations

[Advanced Request Tracing](https://cosmo-docs.wundergraph.com/router/advanced-request-tracing-art.md)[(ART)](https://cosmo-docs.wundergraph.com/router/advanced-request-tracing-art.md) is enabled by default; however, it will only be accessible if you have set `DEV_MODE=true` or `GRAPH_API_TOKEN`. In the latter case, we will exchange a public key from the control plane to ensure that only authorized requests from the Studio can access ART requests. This enables safe debugging of your router in production.

Therefore `DEV_MODE=true` should **NOT** be set when deploying your router to production.

## Recommended resources

The specific resource recommendations depend on your constraints, but we have observed that low to medium-traffic projects benefit from the following setup:

* 3 instances for high availability.

* Each instance is equipped with 2 CPUs and 1GB of RAM.

Thanks to the utilization of Go and internal optimizations, the router demonstrates strong vertical scalability in relation to CPU and memory.

## Custom Config

In Docker and Kubernetes, you can mount configuration files. In that way, you don't have to build a custom Docker image. By default, the router looks for a config at the location where it starts. This location is `/config.yaml` in our official Docker image. You can overwrite the path by setting the `CONFIG_PATH` environment variable.

### Docker

Here we mount the router config from the host system. Take a closer look at `-v` flag.

```bash theme={"system"}
docker run \
    --name cosmo-router \
    -e GRAPH_API_TOKEN=<router_api_token> \
    -e LISTEN_ADDR=0.0.0.0:3002 \
    -v ./config.yaml:/config.yaml \ # Mount the config in the same location as the binary
    -p 3002:3002 \
    ghcr.io/wundergraph/cosmo/router:latest
```

### Kubernetes

In Kubernetes, we have the concepts of volumes and volumeMounts to realize the same behavior as in Docker. Below is a configuration example for the volume only.

```yaml theme={"system"}
apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
        - name: router
          volumeMounts: # Mount the config in the same location as the binary
            - name: router-config
              mountPath: /config.yaml
              subPath: config.yaml
      volumes: # Create a volume from a configMap
        - name: router-config
          configMap:
            name: myConfigMap
```

## Custom Image

In some scenarios, you have to provide a custom Dockerfile, e.g., when you need to build your custom Router binary. Here is an example of how the Dockerfile can look.

```bash theme={"system"}
FROM --platform=${BUILDPLATFORM} golang:1.21 as builder

ARG TARGETOS
ARG TARGETARCH

ARG VERSION=dev
ENV VERSION=$VERSION

WORKDIR /app/

# Copy only the files required for go mod download
COPY go.* .

# Download dependencies
RUN go mod download

# Copy the rest of the files
COPY . .

# Run tests
RUN make test

# Build router
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -trimpath -ldflags "-extldflags -static -X github.com/wundergraph/cosmo/router/core.Version=${VERSION}" -a -o router cmd/custom/main.go

FROM gcr.io/distroless/static-debian13

COPY --from=builder /app/router /router

CMD ["/router"]

EXPOSE 3002
```

If you are wondering about the `BUILDPLATFORM`, `TARGETOS`, `TARGETARCH` arguments, those are needed when building multi-arch images. You can remove them if you don't need them.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.