3: Configuring cloud-native applications for deployment

    Deploying applications to Cloud Run

    Deployment to Cloud Run is the most common cloud-native target on Google Cloud because the runtime collapses three responsibilities that GKE forces the operator to handle separately:

    • container image hosting
    • request-driven autoscaling
    • HTTPS ingress termination

    A service deploy creates an immutable revision, attaches it to a service URL, and routes traffic to it according to a routing policy that the operator can change without redeploying the underlying image. Because revisions are immutable, the deploy surface is also the rollout surface: a gcloud run deploy either produces a new revision or modifies the routing policy, and the right command sequence depends on whether the goal is a code change, a configuration change, a canary, or a fast rollback.

    The decision that drives the rest of this section is whether the deploy reads from source code or from a prebuilt image in Artifact Registry.

    How it works

    Source deploy is shorter to type and ideal for the inner-loop developer experience: gcloud run deploy api --source . triggers Cloud Build buildpacks, detects the language from requirements.txt, package.json, pom.xml, go.mod, or Gemfile, builds an OCI image into a Cloud Build-managed Artifact Registry repository, and deploys the resulting image as a new revision.

    The path is convenient but it bypasses the chapter-2 pipeline:

    • there is no Cloud Build trigger
    • no SLSA provenance generated against a controlled worker pool
    • no Artifact Analysis gate on the upload
    • no Binary Authorization attestation

    For staging and production, the prebuilt-image path is mandatory; the source path remains useful for developer-local smoke tests on a personal project.

    💡 Exam Trap: gcloud run deploy --source does build a container image, contrary to the common misreading that source means a script runtime. The buildpacks produce a real OCI image and push it to a Cloud-Build-managed Artifact Registry repository named cloud-run-source-deploy. Wrong answers describe source deploy as serverless without containerisation.

    💡 Exam Trap: A gcloud run deploy --image ... command without --region will prompt interactively, but in a CI pipeline that prompt becomes a deploy failure. Always pass --region (or set gcloud config set run/region) in non-interactive contexts.

    Deploying applications to Cloud Run from source code

    The source-deploy command line accepts a directory and a service name and produces a running revision in one step.

    The buildpack detection logic looks for language signals in the working directory and pulls a base image from Google's curated set; the build runs on a Cloud Build managed worker pool unless the project specifies a private worker pool through gcloud run deploy --build-worker-pool.

    The build steps are equivalent to the chapter-2 gcloud builds submit --pack flow, but the source deploy bundles the build, the image push, and the Cloud Run revision creation into one transaction.

    If any step fails (buildpack error, image push failure, revision-create failure), the previous revision keeps serving traffic and no partial state is left behind.

    # Source-driven deploy: builds with buildpacks and creates a new revision
    gcloud run deploy payments-api \
     --source . \
     --region europe-west1 \
     --service-account payments-runtime@acme-payments-prod.iam.gserviceaccount.com \
     --memory 512Mi \
     --cpu 1 \
     --concurrency 80 \
     --min-instances 1 \
     --max-instances 50 \
     --ingress all \
     --no-allow-unauthenticated \
     --set-env-vars LOG_LEVEL=INFO,REGION=europe-west1 \
     --set-secrets DATABASE_URL=database-url:latest
    

    The flag set above is the canonical secure shape for a Cloud Run service:

    • a dedicated runtime service account,
    • request-driven concurrency at 80 (the default for buildpack-detected stateless services),
    • a warm pool of one through --min-instances,
    • and a hard cap of 50 instances to bound cost.

    The --no-allow-unauthenticated flag forces every inbound request to carry a Google identity token that the operator authorises through IAM (typically roles/run.invoker granted to an upstream service or to the IAP gate).

    Environment configuration goes through --set-env-vars for non-sensitive values and --set-secrets for sensitive values, where the secret is mounted from Secret Manager into the named environment variable at request time.

    The source-deploy path implicitly enables a Cloud Build step that writes to the project's cloud-run-source-deploy Artifact Registry repository. That repository is created automatically the first time a developer runs source deploy in the project, and the build step needs roles/artifactregistry.writer on the user identity or the build service account.

    For production pipelines the operator should disable source deploy at the org policy layer and force all revisions to come from a pre-attested image in the chapter-2 payments repository; that policy is iam.disableServiceAccountKeyCreation-style but uses the Cloud Run deployment-specific constraints/run.allowedSources constraint where supported.

    Image-based deploy is the path the chapter-2 pipeline produces, and it is the path that interoperates with Binary Authorization. The deploy command refers to an image by digest (never by tag in production, because tags are mutable) and the underlying Binary Authorization policy verifies that the digest carries an attestation from the configured attestor before admitting the revision:

    # Image-driven deploy from the chapter-2 Artifact Registry repository
    gcloud run deploy payments-api \
     --image europe-west1-docker.pkg.dev/acme-payments-prod/payments/api@sha256:b9...e4 \
     --region europe-west1 \
     --service-account payments-runtime@acme-payments-prod.iam.gserviceaccount.com \
     --binary-authorization default \
     --execution-environment gen2 \
     --cpu 1 --memory 512Mi \
     --concurrency 80 --min-instances 1 --max-instances 50 \
     --vpc-egress all-traffic \
     --vpc-connector projects/acme-payments-prod/locations/europe-west1/connectors/payments-conn \
     --no-allow-unauthenticated \
     --tag candidate
    

    The --binary-authorization default flag pins the deployment to the org-default Binary Authorization policy; revision creation fails fast if the image digest lacks a valid attestation.

    The --execution-environment gen2 flag selects the gVisor-backed second-generation execution environment, which supports NFS and Cloud Storage FUSE mounts; first-generation is faster to cold start but lacks those primitives.

    The --tag candidate flag at the end is the blue-green lever: it creates the revision and exposes it on a tagged URL (https://candidate---payments-api-...run.app).

    Combine it with --no-traffic to ensure no production traffic is routed to the new revision — otherwise Cloud Run sends 100% of traffic there by default.

    Traffic only flows after a subsequent gcloud run services update-traffic call.

    📊 Limit: A Cloud Run service holds up to 1,000 revisions in its revision history; older revisions are garbage-collected. Operators who roll back by promoting a stale revision should not rely on revisions older than the retention window; for long-term audit, keep the image digest in a separate ledger.

    ⚠️ Anti-Pattern: Deploying with --image <tag> (a mutable tag like :latest) breaks rollback semantics. The next push to the tag changes what the revision pulled in audit logs, and there is no reliable way to reconstruct which exact image bytes a past revision was running. Always deploy by digest in production.

    Invoking Cloud Run services using triggers

    A Cloud Run service is a synchronous HTTP request handler. Turning it into an event consumer means putting a delivery mechanism in front of the service URL.

    Google Cloud supplies two such mechanisms: Eventarc and Pub/Sub push subscriptions. Each authenticates to Cloud Run with an OIDC token signed by a delivery service account, and each grants roles/run.invoker on the service to that delivery identity.

    When to use

    Eventarc is the preferred mechanism when the event source is a first-party Google Cloud service (Cloud Storage object writes, Audit Log filter matches, Firestore document updates) or an Eventarc-supported third-party provider (the Advanced channel surface).

    Eventarc normalises every event into the CloudEvents 1.0 specification, with ce-id, ce-source, ce-type, ce-specversion, and ce-subject headers on the HTTP request, plus the original payload in the body.

    The same service code can consume from multiple event sources because the CloudEvents envelope is uniform.

    # Create an Eventarc trigger that delivers Cloud Storage finalize events
    gcloud eventarc triggers create payments-csv-ingest \
     --location=europe-west1 \
     --destination-run-service=payments-csv-loader \
     --destination-run-region=europe-west1 \
     --destination-run-path=/events/csv \
     --event-filters="type=google.cloud.storage.object.v1.finalized" \
     --event-filters="bucket=acme-payments-csv-uploads" \
     --service-account=eventarc-delivery@acme-payments-prod.iam.gserviceaccount.com
    

    The eventarc-delivery service account needs three role grants:

    • roles/eventarc.eventReceiver on the project for the source service (Cloud Storage in this case) to call Eventarc
    • roles/run.invoker on the destination Cloud Run service to deliver the event
    • roles/iam.serviceAccountTokenCreator on itself if the delivery uses impersonation

    The --destination-run-path flag routes the inbound POST to a specific path on the service so the handler can multiplex multiple event types into one Cloud Run revision; without it Eventarc defaults to /.

    Pub/Sub push subscriptions are the right answer when the producer is already a Pub/Sub topic publisher and the operator wants exactly-once-style semantics with Pub/Sub's own retry, dead-letter, and ordering keys.

    Pub/Sub push subscriptions do not wrap the message in CloudEvents headers by default; instead the body carries the JSON envelope {"message":{"data":"<base64>","attributes":{...},"messageId":"..."},"subscription":"..."} and the handler is responsible for base64-decoding data and parsing attributes. A push subscription can be configured to use a CloudEvents wire format (BinaryHttpProtoPushConfig), but the legacy default is the Pub/Sub envelope.

    # Pub/Sub push subscription targeting a Cloud Run service
    gcloud pubsub subscriptions create payments-charge-events-push \
     --topic=payments-charges \
     --push-endpoint=https://payments-charge-handler-xyz-ew.a.run.app/events/charges \
     --push-auth-service-account=pubsub-delivery@acme-payments-prod.iam.gserviceaccount.com \
     --push-auth-token-audience=https://payments-charge-handler-xyz-ew.a.run.app \
     --ack-deadline=60 \
     --message-retention-duration=7d \
     --dead-letter-topic=projects/acme-payments-prod/topics/payments-charges-dlq \
     --max-delivery-attempts=10
    

    The --push-auth-service-account flag tells Pub/Sub to attach an OIDC token signed for pubsub-delivery@acme-payments-prod.iam.gserviceaccount.com to every push request.

    Cloud Run validates the token's audience against --push-auth-token-audience (which must match the service URL) and authorises the call by checking that the service account holds roles/run.invoker on the service.

    Pub/Sub retries failed deliveries with exponential backoff.

    After --max-delivery-attempts failures the message moves to the dead-letter topic, where a separate Cloud Run service or Cloud Function can examine and reprocess it.

    💡 Exam Trap: Pub/Sub push subscriptions deliver the message inside an envelope, not as a raw payload. The handler must read request.json["message"]["data"], base64-decode it, and parse it. Wrong answers pretend the body is the raw published bytes; that is only true for pull subscriptions or for CloudEvents-format push subscriptions.

    🎯 Scenario: A fraud-scoring service times out 0.5% of pushed events. The team raises --ack-deadline from 10 seconds to 60 and adds a dead-letter topic with --max-delivery-attempts=10. Failures over 60 seconds are now retried up to 10 times, then routed to the DLQ; the corresponding fix on Cloud Run is to raise --timeout so the request does not exceed the request-execution wall clock before the handler finishes scoring.

    Configuring event receivers for Cloud Run

    A correctly-configured event receiver does four things:

    • validates that the inbound request is genuinely from the expected event source,
    • parses the event payload correctly for the chosen wire format,
    • processes the work idempotently using a deduplication key,
    • and returns the right HTTP status code so the delivery service can decide whether to retry.

    The authentication step on a Cloud Run event receiver works the same way for Eventarc and Pub/Sub push: the delivery system signs an OIDC token with the delivery service account, and Cloud Run validates it before the request reaches the container.

    If the receiver wants its own additional verification (defense in depth), it can read the Authorization: Bearer <token> header and verify the JWT signature, issuer (https://accounts.google.com), audience (the service URL), and the email claim (the expected delivery service account email).

    # A FastAPI Cloud Run handler for both Eventarc CloudEvents and Pub/Sub push.
    import base64
    import json
    from fastapi import FastAPI, Header, HTTPException, Request
    
    app = FastAPI()
    
    @app.post("/events/charges")
    async def handle_charge_event(
     request: Request,
     ce_type: str | None = Header(default=None, alias="ce-type"),
     ce_id: str | None = Header(default=None, alias="ce-id"),
    ):
     body = await request.json()
    
     # Branch on wire format: CloudEvents (Eventarc) vs Pub/Sub envelope.
     if ce_type is not None:
     event_id = ce_id
     payload = body
     else:
     message = body.get("message", {})
     event_id = message.get("messageId")
     data_b64 = message.get("data", "")
     payload = json.loads(base64.b64decode(data_b64))
    
     # Idempotency guard against redelivery storms.
     if already_processed(event_id):
     return {"status": "duplicate", "id": event_id}
    
     process_charge(payload)
     mark_processed(event_id)
    
     # 2xx tells the delivery system the message is acknowledged.
     return {"status": "ok", "id": event_id}
    

    The status-code contract is strict. For Pub/Sub push, any 2xx status acknowledges the message; any non-2xx (or a timeout exceeding --ack-deadline) triggers a retry. For Eventarc, the underlying transport is Pub/Sub for asynchronous sources and a direct HTTP call for synchronous sources, with the same 2xx-acknowledge contract.

    Returning a 4xx for a permanent error (a malformed payload) is the right way to escape the retry loop; returning a 5xx for a transient downstream failure (database unavailable) keeps the message in flight until the operator fixes the dependency or until the dead-letter threshold is reached.

    In practice

    Idempotency on Cloud Run event receivers is the operator's responsibility, not the platform's. Both Eventarc and Pub/Sub guarantee at-least-once delivery, which means duplicates are expected when the receiver crashes mid-process, when the network drops the acknowledgement, or when retry budgets overlap with eventual recovery.

    The receiver must therefore key its work on a stable event ID, typically ce-id for CloudEvents or messageId for Pub/Sub push, and either short-circuit duplicates or apply work in a way that allows the second application to be a no-op (an INSERT ... ON CONFLICT DO NOTHING, a Firestore transaction with a stable document ID, or a Cloud Storage write to a deterministic object path).

    💡 Exam Trap: Returning a 200 inside a try/except that swallows database errors is the canonical wrong answer for a Pub/Sub push receiver. Pub/Sub treats 2xx as acknowledgement; the message is gone, the dead-letter routing never fires, and the failure is invisible. Let the exception bubble, the framework returns 500, and Pub/Sub retries.

    ⚠️ Anti-Pattern: Using --allow-unauthenticated on an event-receiver service to make Eventarc and Pub/Sub work avoids configuring the delivery service account but exposes the endpoint to the public internet. Anyone who guesses the URL can inject events. Always require an OIDC token and authorise the delivery identity through IAM.

    📊 Limit: Cloud Run request execution has a maximum timeout of 3,600 seconds (60 minutes) on gen2 execution environments and 60 minutes on gen1 for HTTP requests. Long-running event work that exceeds these limits should be re-architected as a Cloud Run job triggered by the receiver, or split into smaller messages.

    The Mermaid diagram below captures the end-to-end delivery path from event producer through the trigger surface into the Cloud Run receiver.

    Diagram: Event delivery into Cloud Run

    Versioning, exposing, and securing APIs using Apigee

    Cloud Run is a perfectly valid public HTTPS endpoint, but exposing it directly to a multi-tenant developer audience skips the things an API platform exists to deliver: versioning, deprecation, key issuance, rate limits, quotas, mediation, and analytics.

    Apigee sits between client traffic and the Cloud Run service as a reverse proxy that adds those concerns without changing the upstream code. The Apigee data model is hierarchical.

    • An API proxy is a deployable bundle of policies and a target endpoint.
    • An API product groups one or more proxy resources into a sellable unit.
    • A developer app holds a consumer key and secret that authenticates a particular client against a particular product.

    Apigee environments (typically dev, test, prod) hold deployed proxy revisions; each environment maps to a hostname through an environment group.

    Proxy revisions are immutable, numbered integers; promoting from dev to prod is a redeploy of the same revision number to the prod environment.

    # Excerpt of an Apigee proxy bundle: proxies/default.xml
    - ProxyEndpoint:
     name: default
     PreFlow:
     Request:
     Step: [{Name: VA-Verify-API-Key}, {Name: VJ-Verify-JWT}, {Name: SA-Spike-Arrest}, {Name: Q-Quota-Per-App}]
     HTTPProxyConnection:
     BasePath: /v2/payments
     VirtualHost: [secure]
     RouteRule:
     Name: route-to-cloudrun
     TargetEndpoint: cloudrun-payments
    
    # Excerpt of policies/SA-Spike-Arrest.xml
    - SpikeArrest:
     name: SA-Spike-Arrest
     Rate: 200ps # 200 requests per second, smoothed
     Identifier:
     ref: client.id
    
    # Excerpt of policies/Q-Quota-Per-App.xml
    - Quota:
     name: Q-Quota-Per-App
     Type: calendar
     StartTime: 2000-01-01 00:00:00
     Interval: 1
     TimeUnit: minute
     Allow:
     countRef: verifyapikey.VA-Verify-API-Key.apiproduct.developer.quota.limit
     Identifier:
     ref: client.id
    

    The BasePath in the proxy endpoint encodes the API version segment (/v2/payments); a new major version is a new proxy with a new base path (/v3/payments) routed to a different Cloud Run target.

    Apigee's RouteRule is the cut-over mechanism between two upstreams: a single proxy can hold two targets and route based on a header, query parameter, or weighted distribution, enabling canary releases at the API gateway layer that are independent of the Cloud Run revision routing. The security stack on an Apigee proxy is policy-driven.

    • VerifyAPIKey validates that the inbound x-api-key (or query parameter) matches a published consumer key on an active developer app subscribed to the bound API product.
    • VerifyJWT validates an OAuth 2.0 access token or an OpenID Connect ID token: the policy references a JWKS endpoint (or an inline public key), checks the issuer, audience, expiry, and required claims, and exposes the claims as flow variables for downstream policies.
    • SpikeArrest smooths burst traffic at the configured rate without an enforced counter store; Quota counts requests against a calendar window and enforces the limit defined on the API product.
    # Deploy an Apigee proxy revision and promote it across environments
    apigeecli apis create bundle -f proxies/payments-v2.zip -n payments-v2 -o acme-org
    apigeecli apis deploy -n payments-v2 -v 3 -e dev -o acme-org
    apigeecli apis deploy -n payments-v2 -v 3 -e test -o acme-org
    apigeecli apis deploy -n payments-v2 -v 3 -e prod -o acme-org --override
    

    The --override flag on the production deploy swaps revision 3 in for whatever revision was previously serving production, taking advantage of Apigee's hitless deploy (the in-flight requests finish against the old revision while new requests route to the new one).

    The Apigee API product (defined separately) binds together a set of API proxies and the path suffixes that are allowed under each, plus the developer-facing quota counts that the Q-Quota-Per-App policy reads.

    💡 Exam Trap: Apigee API products are not the same as Apigee API proxies. The proxy is the deployable runtime artifact; the product is the marketable bundle that developer apps subscribe to. A quota lives on the product, not on the proxy. Wrong answers conflate the two.

    💡 Exam Trap: SpikeArrest does not count requests across a window; it smooths burst rate. The Quota policy is the counter-based rate-limit. Pairing the two is the canonical Apigee pattern: SpikeArrest absorbs micro-bursts, Quota enforces the contracted ceiling.

    ⚠️ Anti-Pattern: Exposing a Cloud Run service publicly with --allow-unauthenticated and putting Apigee in front of it without locking down the Cloud Run IAM means a client who discovers the Cloud Run URL bypasses the entire Apigee policy stack. The correct shape is to set the Cloud Run service to --no-allow-unauthenticated and grant roles/run.invoker to the Apigee runtime service account; the proxy then attaches a Google-signed OIDC token to the upstream call (via the Authentication policy with a Google ID token target).

    The decision anchor for source vs image deploy, and for Apigee vs API Gateway:

    • choose gcloud run deploy --source only for personal-project iteration and prototype loops;
    • choose gcloud run deploy --image <digest> for any environment that needs Binary Authorization, provenance, or rollback-by-digest.

    Choose Apigee when the API surface needs versioned products, developer self-service, quota-per-app, OAuth issuance, monetization, or analytics dashboards; choose Cloud API Gateway when the surface is internal-only or partner-only, the volume is moderate, and the team wants a thinner serverless gateway tied to an OpenAPI 2.0 spec without paying for the Apigee runtime. ---

    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the GCP - Professional Cloud Developer learning hub.