Fail over to a standby Kafka cluster with Kong Event Gateway

TL;DR
  1. Connect clients to a virtual cluster instead of to the brokers.
  2. Pre-stage a disabled ACL policy that denies writes.
  3. To fail over, enable the policy and wait for replication to catch up.
  4. Point the virtual cluster at the standby backend cluster.
  5. Run a health check, then disable the policy to resume writes.

Prerequisites

Install kafkactl. You’ll need it to interact with Kafka clusters.

If you don’t have a Konnect account, you can get started quickly with our onboarding wizard.

  1. The following Konnect items are required to complete this tutorial:
    • Personal access token (PAT): Create a new personal access token by opening the Konnect PAT page and selecting Generate Token.
  2. Set the personal access token as an environment variable:

    export KONNECT_TOKEN='YOUR KONNECT TOKEN'

Failing over between Kafka clusters is hard because Kafka clients are tightly coupled to the cluster they connect to:

  • Every client hardcodes the cluster address: Producers and consumers are configured with the bootstrap servers of one cluster. To move them, you have to change the configuration of every application and restart it, often across many teams.
  • Credentials and ACLs are tied to the cluster: The standby cluster needs the same users, credentials, and ACLs as the primary, and clients may need new credentials to reach it.
  • Producers keep writing during the switch: While clients move one by one, some write to the old cluster and some to the new one. Records written to the old cluster after replication stops are lost.
  • Offsets don’t move with the data: Consumer group offsets are stored per cluster, so consumers that switch clusters can skip or reprocess records. See Consumer offsets.

With Kong Event Gateway, clients connect to a virtual cluster instead of to the brokers. The virtual cluster forwards traffic to a backend cluster. Failover becomes a control plane change: you point the virtual cluster at a different backend cluster, and clients keep the same address and credentials.

In this guide, you’ll run a planned failover from a primary cluster to a standby cluster. The following diagram shows how clients connect to the payments virtual cluster, which forwards traffic to primary-kafka before the failover and to secondary-kafka after it:

flowchart LR
    C[Kafka clients] --> VC

    subgraph GW [Event Gateway]
        VC[payments virtual cluster<br/>ACL policies]
    end

    VC -->|before failover| P[(primary-kafka)]
    VC -.->|after failover| S[(secondary-kafka)]
    P -. replication .-> S

To stand in for replication and simplify the demo, this guide creates the same topics on both clusters. In production, use a replication tool such as MirrorMaker 2 or Confluent Cluster Linking to copy records and consumer offsets to the standby cluster.

Start two Kafka clusters

Create a Docker Compose file that defines two single-broker Kafka clusters: a primary cluster named primary-kafka and a standby cluster named secondary-kafka:

cat <<'EOF' > docker-compose.yaml
name: kafka_cluster

networks:
  kafka:
    name: kafka_event_gateway

services:
  primary-kafka:
    image: apache/kafka:4.4.0
    networks:
      - kafka
    container_name: primary-kafka
    ports:
      - "9094:9094"
    environment:
      KAFKA_NODE_ID: 0
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_LISTENERS: INTERNAL://primary-kafka:9092,CONTROLLER://primary-kafka:9093,EXTERNAL://0.0.0.0:9094
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://primary-kafka:9092,EXTERNAL://localhost:9094
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
      KAFKA_CONTROLLER_QUORUM_VOTERS: 0@primary-kafka:9093
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_CLUSTER_ID: 'primaryclusterid000001'
      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs

  secondary-kafka:
    image: apache/kafka:4.4.0
    networks:
      - kafka
    container_name: secondary-kafka
    ports:
      - "9095:9095"
    environment:
      KAFKA_NODE_ID: 0
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_LISTENERS: INTERNAL://secondary-kafka:9092,CONTROLLER://secondary-kafka:9093,EXTERNAL://0.0.0.0:9095
      KAFKA_ADVERTISED_LISTENERS: INTERNAL://secondary-kafka:9092,EXTERNAL://localhost:9095
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
      KAFKA_CONTROLLER_QUORUM_VOTERS: 0@secondary-kafka:9093
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_CLUSTER_ID: 'secondaryclusterid0001'
      KAFKA_LOG_DIRS: /tmp/kraft-combined-logs

EOF

Each broker listens on port 9092 inside the Docker network for Event Gateway connections. For direct local access, the Compose file exposes the primary cluster on port 9094 and the secondary cluster on port 9095.

Start the clusters:

docker compose up -d

Create an Event Gateway control plane and data plane

Run the quickstart script to automatically provision a demo Kong Event Gateway control plane and data plane, and configure your environment:

curl -Ls https://get.konghq.com/event-gateway | bash -s -- -k $KONNECT_TOKEN -N kafka_event_gateway

This sets up an Kong Event Gateway control plane named event-gateway-quickstart, provisions a local data plane, and prints out the following environment variable export:

export EVENT_GATEWAY_ID=your-gateway-id

Copy and paste the command with your Event Gateway ID into your terminal to configure your session.

This quickstart script is meant for demo purposes only, therefore it runs locally with most default parameters and a small number of exposed ports. If you want to run Kong Gateway as a part of a production-ready platform, set up your control plane and data planes through the Konnect UI, or using Terraform.

Create the backend clusters

Create a backend cluster for the primary Kafka cluster:

PRIMARY_CLUSTER_ID=$(curl -X POST "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/backend-clusters" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "primary_cluster",
       "bootstrap_servers": [
         "primary-kafka:9092"
       ],
       "authentication": {
         "type": "anonymous"
       },
       "tls": {
         "enabled": false
       },
       "insecure_allow_anonymous_virtual_cluster_auth": true
     }' | jq -r ".id"
)

Create a second backend cluster for the standby Kafka cluster:

SECONDARY_CLUSTER_ID=$(curl -X POST "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/backend-clusters" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "secondary_cluster",
       "bootstrap_servers": [
         "secondary-kafka:9092"
       ],
       "authentication": {
         "type": "anonymous"
       },
       "tls": {
         "enabled": false
       },
       "insecure_allow_anonymous_virtual_cluster_auth": true
     }' | jq -r ".id"
)

Each backend cluster stores the credentials that Event Gateway uses to connect to that Kafka cluster. When you fail over, the gateway uses the standby cluster’s credentials automatically, so clients don’t need new credentials.

Create a virtual cluster

Create a virtual cluster that points at the primary backend cluster:

VIRTUAL_CLUSTER_ID=$(curl -X POST "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/virtual-clusters" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "payments_vc",
       "destination": {
         "id": "'$PRIMARY_CLUSTER_ID'"
       },
       "dns_label": "payments",
       "authentication": [
         {
           "type": "anonymous"
         }
       ],
       "acl_mode": "enforce_on_gateway"
     }' | jq -r ".id"
)

The virtual cluster uses acl_mode: enforce_on_gateway, so Event Gateway evaluates ACL policies on every request. You’ll use an ACL policy to pause writes during the failover.

Create a listener with a forwarding policy

Create a listener to accept client connections:

LISTENER_ID=$(curl -X POST "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/listeners" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "payments_listener",
       "addresses": [
         "0.0.0.0"
       ],
       "ports": [
         "19092-19095"
       ]
     }' | jq -r ".id"
)

Create a Forward to Virtual Cluster policy to forward traffic to the virtual cluster:

curl -X POST "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/listeners/$LISTENER_ID/policies" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "type": "forward_to_virtual_cluster",
       "name": "forward_to_payments_vc",
       "config": {
         "type": "port_mapping",
         "advertised_host": "localhost",
         "destination": {
           "id": "'$VIRTUAL_CLUSTER_ID'"
         }
       }
     }'

For demo purposes, this guide uses port mapping, which assigns each Kafka broker to a dedicated port on the Event Gateway. In production, we recommend using SNI routing instead.

Allow access to topics and consumer groups

With acl_mode: enforce_on_gateway, clients have no access until an ACL policy grants it. Create an ACL policy that allows all operations on all topics and consumer groups:

curl -X POST "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/virtual-clusters/$VIRTUAL_CLUSTER_ID/cluster-policies" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "type": "acls",
       "name": "allow_all",
       "config": {
         "rules": [
           {
             "resource_type": "topic",
             "action": "allow",
             "operations": [
               {
                 "name": "all"
               }
             ],
             "resource_names": [
               {
                 "match": "*"
               }
             ]
           },
           {
             "resource_type": "group",
             "action": "allow",
             "operations": [
               {
                 "name": "all"
               }
             ],
             "resource_names": [
               {
                 "match": "*"
               }
             ]
           }
         ]
       }
     }'

In production, replace this policy with the access rules your clients need.

Pre-stage the write gate

Create a second ACL policy. This policy will act as a write-gate that denies writes to the orders topic. Create it as enabled: false, so it has no effect until you need it:

GATE_POLICY_ID=$(curl -X POST "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/virtual-clusters/$VIRTUAL_CLUSTER_ID/cluster-policies" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "type": "acls",
       "name": "failover_write_gate",
       "description": "Deny writes to order topics during a failover",
       "enabled": false,
       "config": {
         "rules": [
           {
             "resource_type": "topic",
             "action": "deny",
             "operations": [
               {
                 "name": "write"
               }
             ],
             "resource_names": [
               {
                 "match": "orders"
               }
             ]
           },
           {
             "resource_type": "topic",
             "action": "allow",
             "operations": [
               {
                 "name": "all"
               }
             ],
             "resource_names": [
               {
                 "match": "*"
               }
             ]
           },
           {
             "resource_type": "group",
             "action": "allow",
             "operations": [
               {
                 "name": "all"
               }
             ],
             "resource_names": [
               {
                 "match": "*"
               }
             ]
           }
         ]
       }
     }' | jq -r ".id"
)

When you enable this policy, it must work together with allow_all. Keep the following in mind when you design a write gate:

  • Every enabled ACL policy must allow a request. A request is allowed only if each enabled ACL policy on the virtual cluster allows it. That’s why the gate includes its own allow rules for everything it doesn’t block. A gate that contains only a deny rule blocks all requests, including reads.
  • Deny rules take precedence over allow rules. The order of the rules, and the order of the policies in the chain, doesn’t change the result. Writes to orders are denied even though another rule allows all operations on all topics.
  • List the topics to block explicitly. Because deny rules always take precedence, a gate that denies writes on * also blocks every topic you might want to keep writable. This guide keeps a healthcheck topic outside the gate, so you can test writes against the standby cluster before you resume business traffic.

Configure kafkactl

Create a kafkactl configuration with a context for each Kafka cluster and a vc context that connects through the virtual cluster:

cat <<EOF > kafkactl.yaml
contexts:
  primary:
    brokers:
      - localhost:9094
  secondary:
    brokers:
      - localhost:9095
  vc:
    brokers:
      - localhost:19092
EOF

The vc context represents your applications. Its broker address points to Event Gateway and stays the same throughout the failover.

Create the topics

Create the orders and healthcheck topics on both clusters. In production, your replication tool creates the topics on the standby cluster.

for cluster in primary secondary; do
  kafkactl -C kafkactl.yaml --context $cluster create topic orders
  kafkactl -C kafkactl.yaml --context $cluster create topic healthcheck
done

Produce and consume through the virtual cluster

Produce a record to the orders topic through the virtual cluster:

echo '{"order_id":1,"amount":10}' | kafkactl -C kafkactl.yaml --context vc produce orders

Consume the record as the payments-app consumer group:

kafkactl -C kafkactl.yaml --context vc consume orders --group payments-app --from-beginning --max-messages 1
{"order_id":1,"amount":10}

The consumer group commits its offset. Check it through the virtual cluster:

kafkactl -C kafkactl.yaml --context vc describe consumer-group payments-app

The CONSUMER_OFFSET column shows that payments-app has consumed the first record of orders:

TOPIC      PARTITION     NEWEST_OFFSET     OLDEST_OFFSET     CONSUMER_OFFSET     LEAD     LAG
orders     0             1                 0                 1                   1        0

CLIENT_HOST     CLIENT_ID     GROUP_INSTANCE_ID     TOPIC     ASSIGNED_PARTITIONS

Confirm that the record is stored on the primary cluster:

kafkactl -C kafkactl.yaml --context primary consume orders --from-beginning --exit

Fail over to the standby cluster

1. Stop writes

Enable the write gate:

curl -X PATCH "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/virtual-clusters/$VIRTUAL_CLUSTER_ID/cluster-policies/$GATE_POLICY_ID" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "enabled": true
     }'

The data plane picks up the change within a few seconds. Try to produce a record to orders:

echo '{"order_id":2,"amount":20}' | kafkactl -C kafkactl.yaml --context vc produce orders

Event Gateway rejects the request with the TOPIC_AUTHORIZATION_FAILED error code, so the record never reaches the primary cluster:

0 messages produced
Failed to produce message: kafka server: The client is not authorized to access this topic

If the record is produced, the data plane hasn’t picked up the change yet. Wait a few seconds and try again.

Reads aren’t affected, so consumers keep processing the records that are already on the primary cluster.

Producers that retry on authorization errors wait until you resume writes. Depending on its settings, a producer may report the failed records to the application. Make sure your applications handle TOPIC_AUTHORIZATION_FAILED during a failover.

2. Wait for replication to catch up

Before you switch clusters, make sure that the standby cluster has everything the primary cluster has:

  1. No more writes reach the primary cluster. The incoming byte rate on the primary’s topics, for example the kafka.server:type=BrokerTopicMetrics,name=BytesInPerSec metric, drops to zero.
  2. Replication lag is zero. With MirrorMaker 2, check the lag of the replication consumer group on the primary cluster. With Cluster Linking, check the mirror lag metrics.
  3. Consumer offsets are synced. See Consumer offsets.

This guide doesn’t use replication, so you can continue to the next step.

3. Point the virtual cluster at the standby cluster

Update the virtual cluster’s destination to the secondary backend cluster. The update replaces the whole virtual cluster, so send the complete configuration:

curl -X PUT "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/virtual-clusters/$VIRTUAL_CLUSTER_ID" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "payments_vc",
       "destination": {
         "id": "'$SECONDARY_CLUSTER_ID'"
       },
       "dns_label": "payments",
       "authentication": [
         {
           "type": "anonymous"
         }
       ],
       "acl_mode": "enforce_on_gateway"
     }'

Event Gateway closes the open client connections and forwards new connections to the secondary cluster. Kafka clients reconnect to the same Event Gateway address automatically. Authentication and ACL policies belong to the virtual cluster, so they apply unchanged.

4. Check the standby cluster

Through the virtual cluster, produce a canary record to the healthcheck topic, which the write gate doesn’t block. Then read the topic directly from the secondary cluster to confirm that the virtual cluster now writes there:

echo "canary" | kafkactl -C kafkactl.yaml --context vc produce healthcheck
kafkactl -C kafkactl.yaml --context secondary consume healthcheck --from-beginning --exit
1 messages produced
canary

If the secondary cluster doesn’t return the canary record, the data plane hasn’t picked up the new destination yet. The virtual cluster still wrote the canary record to the primary cluster. Wait a few seconds and run the commands again.

5. Resume writes

Disable the write gate:

curl -X PATCH "https://us.api.konghq.com/v1/event-gateways/$EVENT_GATEWAY_ID/virtual-clusters/$VIRTUAL_CLUSTER_ID/cluster-policies/$GATE_POLICY_ID" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "enabled": false
     }'

Produce a record to orders through the virtual cluster to confirm that writes work again:

echo '{"order_id":3,"amount":30}' | kafkactl -C kafkactl.yaml --context vc produce orders

Validate

Read the orders topic directly from the secondary cluster:

kafkactl -C kafkactl.yaml --context secondary consume orders --from-beginning --exit

The record that you produced after the failover is stored on the secondary cluster:

{"order_id":3,"amount":30}

The client configuration in the vc context never changed. The record that you produced before the failover is still on the primary cluster only, because this guide doesn’t replicate data between the clusters.

Consumer offsets

Event Gateway doesn’t copy or translate consumer group offsets. A consumer group’s committed offsets are stored on the Kafka cluster where the group committed them. The virtual cluster forwards offset requests to the backend cluster in its destination at the time of the request.

You can see this with the payments-app consumer group, which committed its offset before the failover. Describe the group through the virtual cluster again to see that the offset doesn’t carry over:

kafkactl -C kafkactl.yaml --context vc describe consumer-group payments-app

The virtual cluster now points at the secondary cluster, which has no committed offsets for payments-app, so the table is empty:

TOPIC     PARTITION     NEWEST_OFFSET     OLDEST_OFFSET     CONSUMER_OFFSET     LEAD     LAG

CLIENT_HOST     CLIENT_ID     GROUP_INSTANCE_ID     TOPIC     ASSIGNED_PARTITIONS

Next, describe the group directly on the primary cluster to confirm that the offset is still stored there:

kafkactl -C kafkactl.yaml --context primary describe consumer-group payments-app
TOPIC      PARTITION     NEWEST_OFFSET     OLDEST_OFFSET     CONSUMER_OFFSET     LEAD     LAG
orders     0             1                 0                 1                   1        0

CLIENT_HOST     CLIENT_ID     GROUP_INSTANCE_ID     TOPIC     ASSIGNED_PARTITIONS

If payments-app started consuming now, it would have no starting position on the secondary cluster.

What a consumer does after a failover depends on whether its offsets exist on the new cluster:

  • If the offsets were synced to the standby cluster, the consumer resumes close to where it stopped. Offset sync runs on an interval, so the consumer may reprocess a few records committed after the last sync. Design consumers to handle duplicates.
  • If the offsets weren’t synced, the consumer has no committed offset on the new cluster and falls back to its auto.offset.reset setting. If the setting is latest (the default), the consumer skips records that it hadn’t consumed yet. If the setting is earliest, the consumer reprocesses the whole topic.

How offsets reach the standby cluster depends on your replication tool:

  • MirrorMaker 2 copies records to new offsets on the target cluster, so the offsets on the two clusters differ. Its checkpoint connector translates committed offsets, and with sync.group.offsets.enabled=true it writes the translated offsets to the target cluster. MirrorMaker 2 only writes offsets for consumer groups that have no active members on the target cluster.
  • Confluent Cluster Linking keeps the same offsets on mirror topics as on the source topics, and can sync consumer group offsets to the destination cluster.

During a planned failover, check that the offsets of your important consumer groups are synced before you point the virtual cluster at the standby cluster, as described in the section Wait for replication to catch up.

Unplanned failover

During an unplanned failover, skip steps 1 and 2 if the primary cluster is unavailable. In this case, producers are already failing, and there’s nothing left to drain. Check the standby cluster, estimate how much data didn’t replicate before the outage, and then point the virtual cluster at the standby cluster. Records that didn’t replicate are lost, and consumers resume from the last offsets that were synced.

If the primary cluster is still reachable but degraded, for example because of performance problems, use the full planned procedure so that no writes are lost during the switch.

Cleanup

When you’re done experimenting with this example, clean up the resources:

  1. If you created a new Event Gateway control plane and want to conserve your free trial credits or avoid unnecessary charges, delete the new control plane used in this tutorial.

  2. Stop and remove the containers:

    docker-compose down

This will stop all services and remove the containers, but preserve your configuration files for future use.

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!