이 페이지에서는 Cloud Run 서비스 버전에 대한 세션 어피니티를 사용 설정하는 방법을 보여줍니다.
세션 어피니티 작동 방식
기본적으로 세션 어피니티는 사용 설정되어 있지 않으므로 다음과 같이 동일한 클라이언트의 요청이 다양한 인스턴스에서 처리될 수 있습니다.
세션 어피니티를 사용 설정하면 Cloud Run은 지정된 클라이언트의 순차적 요청을 동일한 버전 인스턴스로 라우팅합니다. Cloud Run은 TTL이 30일인 세션 어피니티 쿠키를 사용하고, 다음과 같이 해당 클라이언트의 값을 검사하여 동일한 클라이언트의 여러 요청을 식별하고 이러한 모든 요청을 동일한 인스턴스로 보냅니다.
알아야 할 주요 동작
위 다이어그램과 같이 세션 어피니티를 사용 설정하면 클라이언트가 동일한 인스턴스에 도달합니다. 그러나 인스턴스는 다른 클라이언트의 요청을 수신할 수 있습니다. 세션 어피니티는 인스턴스가 한 클라이언트 전용이라는 의미는 아닙니다.
Cloud Run의 자동 확장 동작으로 인해 세션 어피니티는 최선의 방식의 어피니티입니다. 어떤 이유로든 인스턴스가 종료되거나 최대 요청 동시 실행 수나 최대 CPU 사용률에 도달하면 세션 어피니티가 손상되고 추가 요청이 다른 인스턴스로 라우팅됩니다.
클라이언트 세션 데이터를 인스턴스의 메모리에 캐시할 수 있지만 클라이언트에서 세션 어피니티가 사용 설정되어 있더라도 항상 동일한 인스턴스에 다시 연결된다고 가정할 수 없습니다.
Cloud Load Balancing 세션 어피니티와 Cloud Run 세션 어피니티는 서로 별개의 독립된 세션 어피니티 구현입니다.
부하 분산기 뒤에 있더라도 Cloud Run 서비스에 Cloud Run의 세션 어피니티를 사용 설정할 수 있습니다.
하지만 서버리스 네트워크 엔드포인트 그룹에서는 지원되지 않기 때문에 Cloud Load Balancing 세션 어피니티를 사용 설정할 수 없습니다.
세션 어피니티 및 트래픽 분할
버전 수준에서 세션 어피니티를 사용 설정 또는 중지합니다. Cloud Run 버전에서 세션 어피니티를 사용 설정하고 트래픽 분할도 사용하는 경우 세션 어피니티가 트래픽 분할보다 우선합니다. 극단적으로 세션 어피니티를 사용하는 단일 클라이언트가 모든 요청의 대부분을 담당하는 경우 이러한 요청은 모두 트래픽 분할 구성에 관계없이 지정된 버전으로 라우팅될 수 있습니다.
일부 버전이 세션 어피니티를 사용 설정하고 일부 버전은 사용하지 않는 버전에 트래픽 분할을 사용 설정하면 명시적으로 트래픽 분할 구성을 변경하지 않더라도 요청이 세션 어피니티가 사용 설정된 버전으로 점진적으로 전환됩니다. 그 이유는 세션 어피니티 쿠키가 연결되지 않은 모든 요청에 무작위 분할이 적용되어 결국 일부는 세션 어피니티가 있는 버전에 할당되고 이후에 이러한 요청이 특정 버전에 유지되기 때문입니다.
Cloud Run 서비스의 트래픽 분할 구성을 업데이트할 때 세션 어피니티 쿠키가 연결된 후속 요청이 다른 버전에 할당될 수 있습니다.
Cloud Run은 새 버전으로 리디렉션되는 클라이언트 수를 최소화합니다.
예를 들어 서비스가 90%/10%로 트래픽을 분할하고 트래픽 분할이 80%/20%로 업데이트된 경우, 트래픽의 10%는 현재 트래픽의 20%를 처리하는 버전으로 리디렉션됩니다.
세션 어피니티 설정
구성을 변경하면 새 버전이 생성됩니다. 이를 변경하는 명시적 업데이트가 없으면 이후 버전에도 이 구성 설정이 자동으로 적용됩니다.
세션 어피니티는 새 서비스를 만들거나새 버전을 배포할 때 Google Cloud 콘솔, gcloud 명령줄, .yaml 파일을 사용하여 설정할 수 있습니다.
[[["이해하기 쉬움","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-03(UTC)"],[],[],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."]]