이 페이지에서는 Cloud Tasks 태스크 및 큐의 정의, 사용하는 경우, 사용 방법을 설명합니다. Cloud Tasks를 사용하면 기본 애플리케이션 흐름 외부에서 독립적으로 수행할 수 있는 작업을 분리하여 핸들러를 사용하여 비동기식으로 처리되도록 보낼 수 있습니다.
이처럼 독립적인 작업을 태스크라고 합니다. 예를 들어 사용자 요청을 처리할 때 데이터베이스를 업데이트해야 하지만 이는 시간이 오래 걸릴 수 있습니다. 그 세부정보를 태스크로 오프로드하면 요청으로부터 더 신속하게 처리할 수 있습니다.
오프로드한 태스크는 큐에 추가되고, 태스크가 성공적으로 실행될 때까지 큐는 태스크를 지속합니다. 큐는 초기 구성을 기반으로 전달 흐름 제어 역할을 할 수도 있습니다. 큐를 생성하여 구성하면 Cloud Tasks 서비스에서 큐를 관리합니다. 태스크가 추가되면 큐에서 태스크를 전달하고 작업자가 안정적으로 처리하도록 합니다.
사용자 대상 지연 시간 비용, 서버 다운, 리소스 사용 제한, 재시도 관리와 같은 절차 관련 복잡성은 서비스를 통해 처리됩니다.
Cloud Tasks는 '최소 1회' 전송하도록 설계되었습니다. 따라서 태스크가 성공적으로 추가되면 큐는 태스크를 최소 1회 이상 핸들러에 전송합니다. 드물기는 하지만 여러 작업을 실행할 수 있으므로 반복 실행으로 인해 유해한 부작용이 발생하지 않도록 코드를 작성해야 합니다.
핸들러는 멱등성이 있어야 합니다.
작업 자체는 고유한 이름 및 구성 정보뿐만 아니라 요청을 처리하는 데 필요한 페이로드라고 하는 초기 요청의 모든 데이터(선택사항)로 이루어집니다. 페이로드는 요청 본문으로 전송되므로 페이로드를 포함하는 작업은 POST 또는 PUT를 HTTP 메소드로 사용해야 합니다.
Cloud Tasks API를 사용하여 Cloud Tasks 서비스에 액세스하려면 Google Cloud 프로젝트가 있어야 합니다.
사용 사례
일반적인 사용 사례는 다음과 같습니다.
데이터베이스 업데이트와 같이 잠재적으로 속도가 느린 백그라운드 작업을 작업자에게 위임하여 사용자 응답 속도를 높입니다.
예상치 못한 프로덕션 이슈가 발생하는 경우 요청을 보존합니다.
사용자 대상이 아닌 작업을 기본 사용자 흐름에서 삭제하여 트래픽 급증을 원활하게 처리합니다.
타사 API 호출 비율 관리
HTTP Target이 있는 Cloud Tasks 큐
일반 HTTP Target의 경우 Cloud Tasks 서비스는 태스크 구성 방식에 따라 일반 HTTP 엔드포인트에 있는 작업자에게 태스크 요청을 전달합니다. 이 엔드포인트는 태스크가 구성된 방식에 따라 Cloud Run 함수, Cloud Run, GKE, Compute Engine 또는 온프렘 웹 서버에 있을 수 있습니다. 이러한 큐는 안정적이고 구성 가능한 속도로 요청을 전송합니다. 이를 통해 태스크가 안정적으로 실행됩니다. 성공 시 모든 작업자는 기본 10분, 최대 30분의 제한 시간 전에 HTTP 응답 코드(200-299)를 Cloud Tasks 서비스에 보내야 합니다.
다른 응답이 전송되는 경우나 응답이 없는 경우 태스크를 다시 시도합니다.
Target은 증가하는 작업자를 관리하고 완료되면 태스크를 삭제해야 합니다.
Target에 인증이 필요한 경우 최대 2개의 서비스 계정을 설정해야 합니다. 이때 하나는 클라이언트인 애플리케이션용이고 다른 하나는 큐 자체용입니다. 두 계정 모두에 필수 권한을 부여하고 클라이언트 서비스 계정의 식별자를 태스크 요청에 포함시켜야 합니다. 자세한 내용은 HTTP Target 태스크 만들기를 참조하세요.
App Engine Target이 있는 Cloud Tasks 큐
Cloud Tasks는 다음 App Engine 환경과 호환됩니다.
App Engine 표준 환경 2세대 런타임
App Engine 가변형 환경
현재 Task Queue API를 사용하는 App Engine 1세대 런타임 사용자는 Cloud Tasks로 마이그레이션할 수 있습니다. 자세한 내용은 기존 번들 서비스 마이그레이션을 참조하세요.
번들 태스크 서비스를 사용하지 않는 App Engine 1세대 런타임 사용자는 2세대 런타임으로 업그레이드하여 Cloud Tasks를 사용할 수 있습니다.
App Engine Target의 경우 Cloud Tasks 서비스는 태스크 요청을 핸들러로 전달하지만 이 작업자는 App Engine 내에 있습니다. 따라서 App Engine 핸들러를 타겟팅하는 모든 큐에는 App Engine 앱이 있어야 합니다. 핸들러는 App Engine 앱이 실행되는 리전에서 실행되어야 합니다. 이 리전은 Cloud Tasks 요청의 LOCATION_ID 매개변수로도 사용됩니다.
태스크는 태스크(또는 드물게 큐 자체)의 구성 방식에 따라 라우팅됩니다. 큐는 안정적이고 구성 가능한 속도로 요청을 전송합니다.
이를 통해 태스크가 안정적으로 실행됩니다. 성공 시 모든 작업자는 서비스의 인스턴스 확장 유형에 따라 기한(자동 확장의 경우 10분, 수동 확장의 경우 최대 24시간) 전에 HTTP 응답 코드(200-299)를 Cloud Tasks 서비스에 보내야 합니다. 다른 응답이 전송되는 경우나 응답이 없는 경우 태스크를 다시 시도합니다.
핸들러는 App Engine의 일부이므로 Cloud Tasks 서비스는 태스크의 수많은 프로세스를 관리하므로 트래픽에 맞게 작업자를 증가 및 감소시키고 완료되면 태스크를 삭제합니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2024-12-21(UTC)"],[],[],null,["# Understand Cloud Tasks\n\nThis page describes what Cloud Tasks tasks and queues are, and when\nand how to use them. Cloud Tasks lets you separate out pieces of work\nthat can be performed independently, outside of your main application flow, and\nsend them off to be processed, asynchronously, using *handlers* that you create.\nThese independent pieces of work are called *tasks*. For example, you need to\nupdate a database as part of processing a user request, but updates can be\ntime-consuming. Offloading that detail as a task lets you return from the\nrequest more quickly.\n| **Key Point:** Cloud Tasks is designed for asynchronous work. While Cloud Tasks guarantees delivery of the task itself, it doesn't provide strong guarantees around the timing of task delivery and is therefore unsuitable for interactive applications where a user is waiting for the result.\n\nThe offloaded task is added to a *queue* , which persists the task until it is\nsuccessfully executed or the number of\n[retries](/tasks/docs/configuring-queues#retry) is exhausted, after which it is\ndeleted. Based on your initial configuration, the queue can also act as a\ndispatch flow control. You create and configure the queue which is then managed\nby the Cloud Tasks service. Once tasks are added, the queue\ndispatches them and makes sure they are reliably processed by your workers.\nComplexities associated with that process, such as user-facing latency costs,\nserver crashes, resource consumption limitations, and retry management, are\nhandled by the service.\n\nCloud Tasks is designed to provide \"at least once\" delivery;\nthat is, if a task is successfully added, the queue will deliver it at least\nonce. In some rare circumstances, multiple task execution is possible, so your\ncode must ensure that there are no harmful side-effects of repeated execution.\nYour handlers should be\n[idempotent](https://wikipedia.org/wiki/idempotent).\n\nThe tasks themselves are made up of a unique name and configuration information\nand, optionally, any data from the initial request, called the payload,\nnecessary to process the request. As the payload is sent in the request body,\ntasks that include payloads must use POST or PUT as their HTTP method.\n\nTo access the Cloud Tasks service using Cloud Tasks API , you must\nhave a Google Cloud [project](/resource-manager/docs/creating-managing-projects).\n\n### Features\n\nUsing Cloud Tasks, you can dispatch asynchronous work items with the\nfollowing controls:\n\n- Schedule specific delivery times\n- Manage delivery rates\n- Configure retry behavior\n- Access and manage individual tasks in a queue\n- Enable task deduplication\n\n### General workflow\n\nThe general workflow is as follows:\n\n1. You create a worker to process the tasks.\n2. You create a queue.\n3. You create tasks programmatically and add them to the queue.\n4. The Cloud Tasks service returns an OK to the originating application. This indicates that the task has been successfully written to Cloud Tasks storage, making the create task request both highly available and durable.\n5. The tasks are passed to the worker.\n6. The worker processes the task.\n7. To complete the sequence, the worker returns a 2xx success status code to the Cloud Tasks service.\n\nOnce the task has been handed off to the queue, no data is made available to the\ninitial request.\n| **Note:** The Cloud Tasks API provides an App Engine-independent interface to the App Engine Task Queue service. Queues that are accessible using the App Engine SDK are accessible through the Cloud Tasks API, and queues that are accessible through the Cloud Tasks API are accessible using the App Engine SDK.\n\n### Use cases\n\nTypical use cases include the following:\n\n- Speeding user response times by delegating potentially slow background operations like database updates to a worker\n- Preserving requests in the context of unexpected production incidents\n- Helping smooth traffic spikes by removing non-user-facing tasks from the main user flow\n- Managing third-party API call rates\n\nCloud Tasks queues with HTTP targets\n------------------------------------\n\nIn the case of generic HTTP Targets, the Cloud Tasks service forwards\nthe task request to the worker, located at any generic HTTP endpoint, based on\nhow the task is configured. This endpoint could be on\n[Cloud Run functions](/functions/docs), [Cloud Run](/run/docs),\n[GKE](/kubernetes-engine/docs),\n[Compute Engine](/compute/docs), or even an on-premises web server, based\non how the task is configured. These queues dispatch requests at a reliable,\nconfigurable rate. They ensure reliable task execution; upon success, all\nworkers must send an HTTP response code (200-299) to the Cloud Tasks\nservice before the default timeout deadline of 10 minutes, with a maximum of 30\nminutes. If a different response is sent, or no response, the task is retried.\n\nThe target must manage scaling workers and cleaning up tasks once they are complete.\n\nIf your target requires authentication, you must set up two\n[service accounts](/docs/authentication/getting-started#creating_a_service_account),\none for your application, the client, and one for the queue itself. Both accounts\nmust have been granted the requisite permissions, and an identifier for the\nclient service account must be included in the task request. See\n[Create HTTP Target tasks](/tasks/docs/creating-http-target-tasks#sa) for more\ninformation.\n\nCloud Tasks queues with App Engine targets\n------------------------------------------\n\nCloud Tasks is compatible with the following App Engine\nenvironments:\n\n- App Engine standard environment second-generation runtimes\n- App Engine flexible environment\n\nUsers of App Engine first-generation runtimes who use the\n[Task Queue API](/appengine/docs/standard/services/taskqueue) can migrate to\nCloud Tasks. To learn how, see\n[Migrate off legacy bundled services](/appengine/migration-center/standard/services/migrating-services).\nUsers of App Engine first-generation runtimes who don't use the\nbundled task service can upgrade to second-generation runtimes to use\nCloud Tasks.\n\nIn the case of App Engine targets, the Cloud Tasks service\nalso forwards the task request to the handler, but this worker is located within\nApp Engine. So all queues that target App Engine handlers must\nhave an [App Engine app](/appengine/docs/standard/python/console#create).\nThe handlers must run in the [region](/appengine/docs/locations) where the\nApp Engine app runs. This region also serves as the\n\u003cvar translate=\"no\"\u003eLOCATION_ID\u003c/var\u003e parameter for your Cloud Tasks requests.\n\nThe tasks are routed based on how the task (or, less commonly, the queue itself)\nis configured. The queues dispatch requests at a reliable, configurable rate.\nThey guarantee reliable task execution - upon success, all workers must send an\nHTTP response code (200-299) to the Cloud Tasks service, in this\ninstance before a deadline based on the [instance scaling](/appengine/docs/flexible/python/an-overview-of-app-engine)\ntype of the service: 10 minutes for automatic scaling or up to 24 hours for\nmanual scaling. If a different response is sent, or no response, the task is\nretried.\n\nBecause the handlers are part of App Engine, the Cloud Tasks\nservice itself can do much of the process management for the task, scaling\nworkers up and down in relation to traffic and deleting tasks when they are\ncompleted.\n| **Note:** Two App Engine locations, called `europe-west` and `us-central` in App Engine commands, are called, respectively, `europe-west1` and `us-central1` in Cloud Tasks commands.\n\nSupported regions by target\n---------------------------\n\nIf your target is an **HTTP/S endpoint** , Cloud Tasks is available\nin all [supported Google Cloud regions](/tasks/docs/locations) for\nCloud Tasks.\n\nIf your target is an **App Engine application** located within your\ncurrent project:\n\n- A task targeting App Engine can only be created in the project's\n App Engine [region](/appengine/docs/locations).\n\n- A Google Cloud project can contain only one App Engine app,\n and the region where the App Engine app is located cannot be changed\n once the app is created.\n\n- App Engine is *regional* which means the infrastructure that runs\n your app is located in a specific region. If you want to distribute compute and\n queues across multiple regions, you should target an HTTP/S endpoint instead.\n\n- If you are not using App Engine as a target, you don't need to\n deploy an App Engine app, and you can disable any existing\n App Engine app.\n\nTask deduplication\n------------------\n\nTask deduplication is achieved by assigning a unique name to a task. If you\nattempt to create a task with a name that already exists in the queue, the\ncreation request will fail. This prevents the same task from being added more\nthan once.\n\nCloud Tasks remembers task names for up to 24 hours after the\ntask has been deleted from the queue. Attempting to re-create a task with the\nsame name during this time will also result in a failed request.\n\nIf you don't provide a name when creating a task, Cloud Tasks will\ngenerate a unique name for it, and deduplication is unnecessary.\n\nKey terms\n---------\n\nThe following terms describe key Cloud Tasks capabilities.\n\nObservability\n-------------\n\nYou can monitor and analyze Cloud Tasks activity and growth by\nusing monitoring, logging, and diagnostic tools provided by Google Cloud Observability. For\nmore information see [Observability in Cloud Tasks](/tasks/docs/monitor)."]]