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

# Active-Active Deployment of Tyk AI Studio

> Run Tyk AI Studio in two regions over one replicated PostgreSQL database, and configure Edge Gateways to keep serving when a region or a control plane is lost.

## Availability

| Edition | Deployment Type |
| :- | :- |
| [Community](https://tyk.io/docs/ai-management/ai-studio/overview.md#community-edition) & [Enterprise](https://tyk.io/docs/ai-management/ai-studio/overview.md#enterprise-edition) | Self-Managed |

Active-active deployment is available from Tyk AI Studio 2.3.0.

## Overview

In an active-active deployment, AI Studio runs in two regions at the same time. When you lose one region, the other region continues to operate. Edge Gateways continue to serve traffic and move to the control plane of the other region without help.

## Topology

```mermaid theme={null}
flowchart TB
    subgraph SA["Region A"]
        SA_S["AI Studio replicas<br/>CLUSTER_NODE_LABEL=region-a"]
        SA_PG[("PostgreSQL<br/>primary")]
        SA_E["Edge Gateways<br/>region A control plane first"]
    end
    subgraph SB["Region B"]
        SB_S["AI Studio replicas<br/>CLUSTER_NODE_LABEL=region-b"]
        SB_PG[("PostgreSQL<br/>hot standby")]
        SB_E["Edge Gateways<br/>region B control plane first"]
    end
    W{{"Witness<br/>third location"}}
    SA_S -- "writes" --> SA_PG
    SB_S -- "writes" --> SA_PG
    SA_PG -- "synchronous streaming replication" --> SB_PG
    W -. "decides failover" .-> SA_PG
    W -. "decides failover" .-> SB_PG
    SA_E -- "gRPC" --> SA_S
    SA_E -. "fallback" .-> SB_S
    SB_E -- "gRPC" --> SB_S
    SB_E -. "fallback" .-> SA_S
```

The deployment has these parts:

* **AI Studio replicas in both regions.** All replicas write to the PostgreSQL node that is the primary at that time. The replicas coordinate through the database in the same way as several replicas in one region. One replica is the leader for the work that must run only once.
* **One primary and one hot standby.** The primary is in one region and the standby is in the other region. AI Studio does not read from the standby. Your failover manager promotes it.
* **A witness in a third location.** The witness lets the failover manager decide on a failover safely. Refer to [Add a Witness in a Third Location](#add-a-witness-in-a-third-location).
* **Edge Gateways with two control endpoints.** Each Edge Gateway lists the control plane of its own region first and the other region second.

AI Studio follows a database failover without a restart. The database layer starts the failover and promotes the node. AI Studio never does.

> [!WARNING]
>
> Multi-primary PostgreSQL is not supported. This includes BDR, bidirectional logical replication, and other setups that accept writes on two nodes. AI Studio uses sequences for IDs and advisory locks for migrations and leader election. With two primaries, two replicas can get the same IDs, and two replicas can each act as the leader.

## Database Requirements

* PostgreSQL 14 or later. The failover behavior on this page is tested with PostgreSQL 16.
* PostgreSQL with physical streaming replication. Put the primary in one region and a hot standby in the other region (`hot_standby = on`).
* Synchronous replication between the regions (recommended). On the primary, set `synchronous_commit = on` and set `synchronous_standby_names` to the standby of the other region.
  * A commit then completes only after the standby has it.
  * If you lose the region of the primary, you lose no committed data.
* Automatic failover. Use a managed PostgreSQL service with cross-zone or cross-region high availability.
* NTP on the database nodes and on the AI Studio replicas. The leader lease of AI Studio allows for a clock difference of up to 30 seconds after a failover. Larger differences are not supported.

### Add a Witness in a Third Location

Two regions cannot decide on a failover safely by themselves. When region A loses contact with region B, region A cannot tell if region B is down or if only the link is down.

If each region promotes its own node, both nodes accept writes. This is split brain, and you lose the writes of one side when the regions join again.

A witness in a third location breaks the tie. Use one of these:

* The control plane of a managed PostgreSQL service
* A Kubernetes API server, or a CloudNativePG or Patroni quorum, across three zones
* A witness node in a third region, such as an etcd, Consul, or ZooKeeper member

Without a third location, an administrator must decide that a region is lost and [promote the standby manually](#promote-the-standby-manually). Until the promotion, there is no primary and AI Studio cannot save changes.

## Configure AI Studio

### Database Connection String

Give every AI Studio replica in both regions the same multi-host connection string. Set `target_session_attrs=read-write`, so that the driver connects to the node that accepts writes:

```bash theme={null}
DATABASE_URL=postgres://studio:secret@pg-a.example.internal:5432,pg-b.example.internal:5432/studio?target_session_attrs=read-write&sslmode=require&connect_timeout=3
```

* List the node of your own region first. The driver tries the hosts in order. A node that does not answer costs the full connect timeout before the driver tries the next host.
* Set a short connect timeout. Use `connect_timeout=3` in the URL, or set `DATABASE_CONNECT_TIMEOUT`.
* Set an explicit `sslmode`, such as `require` or `verify-full`.

### Failover and Cluster Settings

| Variable | Description |
| :- | :- |
| [DATABASE\_WRITE\_RETRY\_WINDOW](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#database_write_retry_window) | How long AI Studio holds and retries a database statement while no node accepts writes. After this time, the request gets `503`. Set it longer than the detection time plus the promotion time of your failover manager. |
| [DATABASE\_READY\_GRACE](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#database_ready_grace) | How long `/ready` stays `200` after the database stops accepting writes. Keep it longer than `DATABASE_WRITE_RETRY_WINDOW`, or AI Studio logs a warning at startup. |
| [DATABASE\_CONNECT\_TIMEOUT](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#database_connect_timeout) | The connect timeout for each database host. |
| [DATABASE\_STARTUP\_TIMEOUT](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#database_startup_timeout) | How long a replica waits at startup for a writable database. |
| [CLUSTER\_NODE\_LABEL](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#cluster_node_label) | A label for the replica, such as `region-a` or `region-b`. Set a different value in each region. When not set, the replica has no label. |
| [QUEUE\_TYPE](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#queue_type) | Set `postgres`, or `nats` with a NATS server that both regions can reach. The default in-memory queue works only on one replica, so chat sessions break when a request goes to another replica. |

The **Held by** column of the **Edge Gateways** page shows the label of the replica that holds each Edge Gateway. The column shows when more than one replica holds Edge Gateways.

For all AI Studio variables, refer to [AI Studio Environment Variables](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md).

### Settings That Must Match in Both Regions

| Setting | Why it must match |
| :- | :- |
| [TYK\_AI\_SECRET\_KEY](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#tyk_ai_secret_key) | It encrypts secrets at rest. AI Studio also finds App keys by a hash keyed with it. With a different value, no App key validates. |
| [MICROGATEWAY\_ENCRYPTION\_KEY](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#microgateway_encryption_key) | It encrypts the configuration that AI Studio sends to Edge Gateways, and it keys the credential hashes that Edge Gateways receive. |
| [GRPC\_AUTH\_TOKEN](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#grpc_auth_token) (and [GRPC\_AUTH\_TOKEN\_NEXT](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#grpc_auth_token_next) during a rotation) | Edge Gateways use one token for the control plane of either region. |
| [CSRF\_KEY](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#csrf_key) | It signs the forms of the admin UI and the AI Portal. You must set it when you run more than one replica. |
| [DATABASE\_URL](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#database_url) | All replicas use the same database, with both hosts listed. If you set `DATABASE_SCHEMA`, use the same value. |
| [TYK\_AI\_LICENSE](https://tyk.io/docs/ai-management/ai-studio/ai-studio-env.md#tyk_ai_license) (Enterprise) | One license covers both regions. |
| AI Studio version | Both regions run the same release. |
| TLS certificates for gRPC port `50051` | The certificates must be valid for the control endpoints of both regions, from a CA that your Edge Gateways trust. |
| Plugins | Install plugins from the marketplace or an OCI registry. A plugin from a file (`file://`) must exist at the same path on every replica in both regions. |

AI Studio compares the first four secrets across the live replicas, and the cluster status shows a warning when they differ. A replica with a different value still starts, so that you can roll a rotation through the replicas.

You cannot rotate `TYK_AI_SECRET_KEY` or `MICROGATEWAY_ENCRYPTION_KEY` on a running deployment. Refer to [Secrets Management](https://tyk.io/docs/ai-management/ai-studio/secrets.md) and [Shared Secrets Reference](https://tyk.io/docs/ai-management/ai-studio/deployment-k8s.md#shared-secrets-reference).

### Load Balancers and Health Checks

* Put the UI and API of both regions behind one name with session affinity.
  * Chat sessions, agent conversations, and MCP connections over SSE stay on the replica that started them.
  * Sign-in sessions are in the database, so they continue on the other region.
* Use `GET /health` for liveness. It does not check the database.
* Use `GET /ready` for readiness. The response body reports the database state as `writable`, `read_only`, or `unreachable`.
  * `/ready` stays `200` during a database failover that is shorter than `DATABASE_READY_GRACE`. Thus, a failover does not remove all replicas from the load balancer.
* Use `GET /ready?require=write` if the load balancer must send traffic only to replicas that can save changes. It returns `200` only while the database accepts writes, with the same grace period.
* Give the gRPC port (`50051`) of each region its own address. A load balancer in front of this port must support HTTP/2. It must keep idle streams open for at least one minute.
* Keep DNS available inside each region. If a region reaches its DNS server only across the link between the regions, a link failure stops name resolution. On Kubernetes, run a DNS replica in each zone and route lookups to the replica in the same zone.

## Configure Edge Gateways

### Two Control Endpoints

Set `CONTROL_ENDPOINTS` on each Edge Gateway. List the control plane of its own region first:

```bash theme={null}
# Edge Gateway in region A
CONTROL_ENDPOINTS=cp-a.example.com:50051,cp-b.example.com:50051

# Edge Gateway in region B
CONTROL_ENDPOINTS=cp-b.example.com:50051,cp-a.example.com:50051
```

The Edge Gateway connects to the first endpoint that accepts it. When the connection fails, it tries the other endpoints immediately, in list order. It waits only after all endpoints fail, and continues to serve traffic while it reconnects.

Do not set `CONTROL_ENDPOINT` and `CONTROL_ENDPOINTS` together. The Edge Gateway does not start if you set both.

### Edge Gateway Settings

| Variable | Description |
| :- | :- |
| [CONTROL\_ENDPOINTS](https://tyk.io/docs/ai-management/ai-studio/edge-gateway-env.md#control_endpoints) | An ordered, comma-separated list of control planes (`host:port`). List the control plane of the same region first. |
| [EDGE\_RECONNECT\_INTERVAL](https://tyk.io/docs/ai-management/ai-studio/edge-gateway-env.md#edge_reconnect_interval) | The first wait after all endpoints fail. The wait doubles up to 30 seconds. |
| [EDGE\_CONTROL\_FAILBACK\_INTERVAL](https://tyk.io/docs/ai-management/ai-studio/edge-gateway-env.md#edge_control_failback_interval) | How often an Edge Gateway that is not on its first endpoint tries to go back to it, for example `5m`. With `0`, the Edge Gateway stays on the other control plane until that connection ends. |

For the other settings that keep an Edge Gateway running during an outage, refer to [Edge Gateway Resilience](https://tyk.io/docs/ai-management/ai-studio/edge-gateway-resilience.md#outage-settings).

### Start Without a Control Plane

By default, an Edge Gateway that starts while no control plane answers exits. To let it start from the configuration that it last applied, set `EDGE_START_FROM_LAST_KNOWN_GOOD=true`. Refer to [Start Without a Control Plane](https://tyk.io/docs/ai-management/ai-studio/edge-gateway-resilience.md#start-without-a-control-plane).

### Full Credential Sync (Enterprise)

With `EDGE_CREDENTIAL_SYNC=full`, an Edge Gateway validates App keys from a hashed list, with or without a control plane. Refer to [Full Credential Sync](https://tyk.io/docs/ai-management/ai-studio/edge-gateway-resilience.md#full-credential-sync-enterprise).

### Size Edge Gateways for the Loss of a Region

After you lose a region, the Edge Gateways of the other region carry all traffic. Size the Edge Gateways of each region for the load of both regions. During a control-plane outage, each Edge Gateway also holds its undelivered analytics in memory. For sizing guidance, refer to [Scaling Edge Gateways](https://github.com/TykTechnologies/ai-studio/blob/main/docs/site/docs/deployment-helm-k8s.md#scaling-edge-gateways).

## What Happens During a Failover

### Requests While There Is No Primary

Between the loss of the primary and the promotion of the standby, no node accepts writes. AI Studio holds the database statement of a request and tries it again until a writable node answers, for up to `DATABASE_WRITE_RETRY_WINDOW`:

* If the promotion completes inside the window, the request waits a few seconds and then succeeds once. AI Studio creates an App or a key only once during an automatic failover.
* If no promotion completes inside the window, the request gets `503` with `Retry-After` and the error code `database_unavailable`.
* Sign-in requests and requests with a session or an API key also get `503`, and never `401`. Clients then retry and keep their credentials.
* AI Studio does not queue a request after the window. The client sends the request again.

Some statements fail immediately and are not held:

* A statement in a transaction that was already open when the primary was lost
* A statement that may have reached the server
* New statements when 512 statements are already held on the replica
* Calls from Edge Gateways to the control plane, so that an Edge Gateway moves to the other region without delay

A running Edge Gateway continues to serve from its loaded configuration during a database failover.

### Failure Scenarios

1. **You lose a whole region (AI Studio and its PostgreSQL node).**
   * The Edge Gateways of that region move to the control plane of the other region.
   * If the lost node was the primary, the failover manager promotes the standby. The AI Studio replicas in the other region then write to it without a restart.
   * A surviving replica becomes the leader within about 30 seconds.
   * You need a witness for automatic failover, and capacity in each region for all traffic.
2. **You lose the PostgreSQL primary, and both AI Studio regions are up.**
   * AI Studio holds requests for up to `DATABASE_WRITE_RETRY_WINDOW`. They complete after the promotion, or they get `503`.
   * `/ready` stays `200` for `DATABASE_READY_GRACE`.
   * You need a promotion time shorter than `DATABASE_WRITE_RETRY_WINDOW`, and `DATABASE_READY_GRACE` longer than both.
3. **A primary is demoted but continues to run (a switchover).**
   * Writes on the old primary fail. AI Studio detects this at the first refused write, or within 5 seconds when idle. It then reconnects to the new primary.
   * You need no action.
4. **You lose AI Studio in one region, and its database node is up.**
   * The Edge Gateways of that region move to the other region. The load balancer stops sending traffic there.
   * Users on that region can lose an open chat session.
   * You need session affinity that fails over. Set `EDGE_CONTROL_FAILBACK_INTERVAL` if Edge Gateways must return when the region is back.
5. **You lose the link between the regions.**
   * The region without the primary cannot write. After `DATABASE_READY_GRACE`, its `/ready` returns `503` and the load balancer stops sending traffic there.
   * Its Edge Gateways continue to serve traffic.
   * The failover manager must not promote the standby unless a witness confirms that the region of the primary is lost.
   * You need a witness, alerts on `aistudio_db_writable`, and DNS that answers inside each region.
6. **An Edge Gateway restarts during a control-plane outage.**
   * It exits, unless `EDGE_START_FROM_LAST_KNOWN_GOOD=true` and its database is on a persistent volume.
   * It validates keys only with full credential sync.
   * You need a decision on last-known-good, and persistent volumes.

## Promote the Standby Manually

Use this procedure when you have no witness and an administrator decides that the region of the primary is lost:

1. Make sure that the old primary cannot accept writes. Stop it, or isolate it from the network (fence it). If you promote the standby while the old primary can still accept writes, you get split brain.
2. Promote the standby. Use `pg_ctl promote` or `SELECT pg_promote()` on the standby, or the command of your failover manager.
3. Clear `synchronous_standby_names` on the new primary. Otherwise every commit waits for a standby that is not there.
4. Check that the AI Studio replicas write to the new primary. The `aistudio_db_writable` metric is `1` on each replica, and the cluster status shows all replicas.

AI Studio replicas connect to the new primary without a restart. Writes that were held for longer than `DATABASE_WRITE_RETRY_WINDOW` before the promotion got `503`, and users must make these changes again.

### Bring the Old Primary Back as a Standby

Do not start the old primary as a primary next to the promoted node:

1. Rebuild the old primary as a standby of the new primary. Use `pg_rewind`, a new `pg_basebackup`, or the reinit command of your failover manager.
2. Wait until it streams, then make it synchronous again.
3. Start the AI Studio replicas of that region. They wait for a writable database for up to `DATABASE_STARTUP_TIMEOUT`, then join the cluster.

To move the primary back to the original region, do a planned switchover with your failover manager. Edge Gateways return to the control plane of their own region when their current connection ends, or within `EDGE_CONTROL_FAILBACK_INTERVAL` if you set it.

## Monitoring

| Signal | Source | Alert when |
| :- | :- | :- |
| `aistudio_db_writable` | AI Studio metrics | It is `0` for longer than the promotion time of your failover manager. |
| `aistudio_db_failovers_total` | AI Studio metrics | It increases. A failover happened. |
| `aistudio_db_write_retries_total`, `aistudio_db_writes_held`, `aistudio_db_unavailable_responses_total` | AI Studio metrics | Requests get `503` during a failover. |
| Cluster status | AI Studio API | A warning shows, a replica is missing, or there is no leader. |
| `microgateway_control_connected{endpoint}` | Edge Gateway metrics | The first endpoint of an Edge Gateway is `0` for a long time. The Edge Gateway is on the other region. |
| `microgateway_config_source{source}` and `microgateway_config_age_seconds` | Edge Gateway metrics | The source `last_known_good` is `1`, or the age is near `EDGE_LAST_KNOWN_GOOD_MAX_AGE`. |
| `microgateway_analytics_pulse_dropped_records_total` | Edge Gateway metrics | It increases. The Edge Gateway lost analytics during an outage. |
| `microgateway_credential_sync_last_success_timestamp` | Edge Gateway metrics | The time since the last sync is near `EDGE_CREDENTIAL_SYNC_MAX_AGE`. |
| Replication lag and `sync_state` | PostgreSQL `pg_stat_replication` or your managed service | The standby is not synchronous, or it lags. |

The cluster status is available from the AI Studio API at `/api/v1/cluster/status`. It requires read access to Edge Gateways. Refer to the [AI Studio API reference](https://tyk.io/docs/ai-management/ai-studio/ai-studio-swagger.md). For metrics setup, refer to [Observability](https://tyk.io/docs/ai-management/ai-studio/observability.md).
