[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-04 (世界標準時間)。"],[],[],null,["# Set session affinity for services\n\nThis page shows how to enable session affinity for your Cloud Run\nservice revision.\n\nHow session affinity works\n--------------------------\n\nBy default, session affinity is not enabled, so requests from\nthe same client might be handled by different instances, as shown\nhere:\n\nIf you enable session affinity, Cloud Run routes sequential requests\nfor a given client to the same revision instance. Cloud Run\nuses a session affinity cookie with a TTL of 30 days, and inspects its value to\nidentify multiple requests by the same client and directs all these requests to\nthe same instance, as shown here:\n\nKey behaviors to be aware of\n----------------------------\n\nAs shown in the diagram above, with session affinity enabled, a client will reach the\nsame instance. However, note that the instance can receive\nrequests from different clients. Session affinity does not mean that the\ninstance is dedicated only to one client.\n\nDue to the autoscaling behavior of Cloud Run, session affinity is\n*best effort* affinity. If the instance is terminated for any reason, or reaches\nmaximum request concurrency or maximum CPU utilization, then session\naffinity is broken and further requests are routed to a different instance.\n\nAlthough you can cache client session data in memory of instances,\nyou cannot assume that a client will always reconnect to the same instance,\n*even when session affinity is enabled*.\n\n[Cloud Load Balancing session affinity](/load-balancing/docs/backend-service#session_affinity) and Cloud Run session affinity are two separate and independent implementations of session affinity.\nYou can enable Cloud Run's session affinity on a Cloud Run service, even if it's behind a load balancer.\nHowever, you shouldn't enable Cloud Load Balancing session affinity on a [serverless network endpoint group](/load-balancing/docs/negs/serverless-neg-concepts#traffic-management), since it's\nnot supported.\n\nSession affinity and traffic splitting\n--------------------------------------\n\nYou enable or disable session affinity at the revision level. If you\nenable session affinity on a Cloud Run revision and also use\n[traffic splitting](/run/docs/rollouts-rollbacks-traffic-migration#split-traffic),\nsession affinity takes precedence over any traffic splitting. In extreme cases, if\na single client using session affinity is responsible for a vast majority of all\nrequests, all of those requests can be routed to a given revision regardless of\nthe traffic splitting configuration.\n\nIf you enable traffic splitting for revisions where some of the revisions have session\naffinity enabled and some do not, the result is that requests are gradually shifted\ntowards revisions that have session affinity enabled, even though you do not explicitly\nchange the traffic split configuration. The reason for this is that every request\nthat doesn't have a session affinity cookie attached is subject to a random split,\nwhere some will eventually be assigned to a revision with session affinity and\nsubsequently those requests will stay with that particular revision.\n\nWhen updating the traffic splitting configuration for a Cloud Run\nservice, subsequent requests with session affinity\ncookies attached might be assigned to a different revision.\nCloud Run minimizes the number of clients that are\nredirected to a new revision.\n\nFor example, if a service was splitting traffic at 90%/10%, and the traffic\nsplit is updated to 80%/20%, then 10% of the traffic will be redirected to\nthe revision that is now serving 20% of the traffic.\n\nSet session affinity\n--------------------\n\nAny configuration change leads to the\ncreation of a new revision. Subsequent revisions will also automatically get\nthis configuration setting unless you make explicit updates to change it.\n\nYou can set session affinity using the Google Cloud console, the\ngcloud command line, or using a .yaml file when you\n[create a new service](/run/docs/deploying#service) or\n[deploy a new revision](/run/docs/deploying#revision): \n\n### Console\n\n\n1. In the Google Cloud console, go to Cloud Run:\n\n [Go to Cloud Run](https://console.cloud.google.com/run)\n2. Select **Services** from the menu, and click **Deploy container** to\n configure a new service.\n If you are configuring an existing service, click the\n service, then click **Edit and deploy new revision**.\n\n3. If you are configuring a new service, fill out the initial service\n settings page, then click **Container(s), Volumes, Networking, Security** to expand the\n service configuration page.\n\n4. Click the **Networking** tab.\n\n - Click the *Session affinity* text box.\n5. Click **Create** or **Deploy**.\n\n### gcloud\n\nTo specify session affinity, use the following command:\n\n\u003cbr /\u003e\n\n```bash\ngcloud run services update SERVICE --session-affinity\n```\n\n\u003cbr /\u003e\n\nReplace\n\n- \u003cvar translate=\"no\"\u003eSERVICE\u003c/var\u003e with the name of the service you are updating.\n\nTo remove session affinity, use the command\n\n\u003cbr /\u003e\n\n```bash\ngcloud run services update SERVICE --no-session-affinity\n```\n\n\u003cbr /\u003e\n\n### YAML\n\n1. If you are creating a new service, skip this step.\n If you are updating an existing service, download its [YAML configuration](/run/docs/reference/yaml/v1):\n\n ```bash\n gcloud run services describe SERVICE --format export \u003e service.yaml\n ```\n2. Add the `run.googleapis.com/sessionAffinity:` annotation:\n\n ```yaml\n spec:\n template:\n metadata:\n annotations:\n run.googleapis.com/sessionAffinity: '\u003cvar translate=\"no\"\u003eBOOL\u003c/var\u003e'\n ```\n\n Replace\n - '\u003cvar translate=\"no\"\u003eBOOL\u003c/var\u003e' with value '`true`' to set session affinity, or '`false`' to remove session affinity.\n3. Create or update the service using the following command:\n\n ```bash\n gcloud run services replace service.yaml\n ```\n\n### Terraform\n\n\u003cbr /\u003e\n\nTo learn how to apply or remove a Terraform configuration, see\n[Basic Terraform commands](/docs/terraform/basic-commands).\nAdd the following to a [`google_cloud_run_v2_service`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/cloud_run_v2_service) resource in your Terraform configuration: \n\n\u003cbr /\u003e\n\n resource \"google_cloud_run_v2_service\" \"default\" {\n name = \"cloudrun-service-aff\"\n location = \"\u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e\"\n deletion_protection = false\n ingress = \"INGRESS_TRAFFIC_ALL\"\n\n template {\n containers {\n image = \"us-docker.pkg.dev/cloudrun/container/hello\"\n }\n session_affinity = \u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-err\"\u003eBOOL\u003c/span\u003e\u003c/var\u003e\n }\n }\n\nReplace:\n\n- \u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e with the Google Cloud region. For example, `europe-west1`.\n- \u003cvar translate=\"no\"\u003eBOOL\u003c/var\u003e with value `true` to set session affinity, or `false` to remove session affinity.\n\nView session affinity settings\n------------------------------\n\nTo view the current session affinity settings for your\nCloud Run service: \n\n### Console\n\n1. In the Google Cloud console, go to Cloud Run:\n\n [Go to Cloud Run](https://console.cloud.google.com/run)\n2. Click the service you are interested in to open the **Service details**\n page.\n\n3. Click the **Revisions** tab.\n\n4. In the details panel at the right, the session affinity setting\n is listed under the **Networking** tab.\n\n### gcloud\n\n1. Use the following command:\n\n ```bash\n gcloud run services describe SERVICE\n ```\n2. Locate the session affinity setting in the returned\n configuration."]]