4: Integrating applications with Google Cloud services

    Integrating an application with data and storage services

    The compute platform decisions from chapter 1 and the deployment topology from chapter 3 only matter once the running service actually opens a database connection, writes an object to Cloud Storage, or publishes a message to a topic.

    The data-plane integration patterns covered here are where most production incidents originate:

    • a Cloud SQL instance exhausting its connection slots because the service forgot to use a pool,
    • a Firestore transaction silently retrying twelve times because the read set crossed a composite-index boundary,
    • a Pub/Sub publisher dropping messages because the in-flight quota was set too low.

    The section walks the connection-management shape for each store, then the read and write API patterns, and closes on Pub/Sub publish-and-consume from inside the application.

    Managing connections to Cloud SQL, Firestore, and Cloud Storage

    How it works

    Cloud SQL connection management has three supported paths from a Google-Cloud-hosted workload:

    • The Cloud SQL Auth Proxy as a local sidecar that opens a TLS-wrapped tunnel to the instance over IAM.
    • The Cloud SQL Language Connectors (Python, Java, Go, Node), which embed the same proxy logic into a database driver.
    • The Cloud Run built-in connection that exposes the instance through a Unix socket at /cloudsql/<INSTANCE_CONNECTION_NAME>.

    The Auth Proxy and the language connectors both resolve the instance through the Cloud SQL Admin API, exchange short-lived credentials, and pin the TLS certificate, which removes the operator burden of running a public IP, an authorized network list, or a long-lived password file. The built-in Cloud Run connection wraps that same proxy but configures it for you when you pass --add-cloudsql-instances=<CONNECTION_NAME> at deploy time.

    AlloyDB follows the same shape with a parallel AlloyDB Auth Proxy and AlloyDB language connectors.

    Both Cloud SQL and AlloyDB support IAM database authentication, where the database role is mapped to an IAM principal (a service account or a user) and the password is replaced by an OAuth 2.0 access token. The driver requests the token through Application Default Credentials, which means production workloads on Cloud Run or GKE never need to read a database password from Secret Manager when IAM auth is enabled. Password auth remains available for legacy clients, in which case the password is stored in Secret Manager and read at startup.

    💡 Exam Trap: The Cloud SQL Auth Proxy and the Cloud SQL connector library both pin to the instance through INSTANCE_CONNECTION_NAME (project:region:instance), not through a hostname or an IP. Stems that talk about "configuring the database host" are usually wrong; the connection identifier is the project-region-instance tuple, and the IP path is the legacy approach the exam expects you to flag as the lower-security option.

    Connection pooling sits one layer above the connector.

    Cloud Run scales to zero, then back up to many instances; each instance opens its own pool, and the aggregate connection count across all instances must stay under the Cloud SQL max_connections limit.

    The recommended pattern is a small per-instance pool (5 to 10 connections) combined with the Cloud SQL instance configured for the right tier:

    • a 1 vCPU shared instance allows roughly 100 connections
    • an 8 vCPU dedicated instance allows 1,000+

    On GKE the same arithmetic applies, multiplied across pods.

    The Cloud SQL connector documentation also calls out that lazy-refresh connections, which silently reopen on idle expiry, prevent the "stale-after-15-minutes" failure mode the Auth Proxy used to exhibit.

    # app.py - Cloud SQL Python connector with IAM authentication
    import os
    from google.cloud.sql.connector import Connector, IPTypes
    import sqlalchemy
    
    connector = Connector()
    
    def getconn():
     conn = connector.connect(
     os.environ["INSTANCE_CONNECTION_NAME"], # project:region:instance
     "pg8000",
     user=os.environ["DB_IAM_USER"], # service-account email
     db=os.environ["DB_NAME"],
     enable_iam_auth=True,
     ip_type=IPTypes.PRIVATE,
     )
     return conn
    
    engine = sqlalchemy.create_engine(
     "postgresql+pg8000://",
     creator=getconn,
     pool_size=5,
     max_overflow=2,
     pool_timeout=30,
     pool_recycle=1800,
    )
    

    Firestore connection management is simpler because the client library speaks gRPC over HTTP/2 to a global endpoint, and the SDK keeps a single multiplexed channel per process.

    The application picks Firestore Native mode for new builds (the Datastore-mode SDK is the legacy entity API).

    On Cloud Run, Firestore reads from the same process-level channel scale automatically with concurrent requests up to the per-instance concurrency setting from chapter 3; on GKE, the same channel is shared by goroutines or threads inside one pod.

    The only knob worth tuning is the channel pool size, available on Java and Go clients for very high-throughput workloads.

    Cloud Storage connections are HTTP/1.1 to a regional or multi-regional endpoint; HTTP/2 is supported in gRPC-capable client builds.

    The Storage client library opens an HTTPS connection pool whose size scales with concurrent requests.

    There is no "connection limit" in the Cloud SQL sense; the practical limits are the Cloud Storage per-bucket QPS budget (covered in the Limits subsection below) and the per-instance egress bandwidth.

    The connection shape for very large objects matters more than the connection count: resumable uploads chunked into 256 KiB multiples survive process restarts, while streaming uploads keep the connection open through the entire payload and fail the whole upload on a network blip.

    📊 Limit: Cloud SQL connection ceilings scale with machine size. Default max_connections: shared-core (db-f1-micro, db-g1-small) approximately 25 to 50; 1 vCPU dedicated instances approximately 100; 4 vCPU approximately 400; 16+ vCPU approximately 1,000 to 4,000. Always validate against SHOW max_connections; in the instance you deployed; flag-based overrides are supported, but raising the ceiling does not change the per-connection memory cost, which is roughly 10 MiB per PostgreSQL backend.

    ⚠️ Anti-Pattern: Opening a new database connection on every HTTP request. Cloud Run revisions and GKE pods are long-lived; the connection pool belongs in module-level state, not in the request handler. A fresh connection per request will exhaust max_connections under load and add 50 to 200 ms of TLS handshake latency to every call.

    Reading from and writing to data sources

    Read and write semantics differ enough across the three stores that the SDK shape is exam-testable for each.

    Cloud SQL uses the relational driver pattern: prepared statements, transactions, and explicit COMMIT or ROLLBACK. The Cloud SQL connector library returns a DB-API or JDBC connection that behaves like any other PostgreSQL or MySQL client; the application owns transaction boundaries, isolation levels, and serializable retry on 40001 errors.

    PostgreSQL on Cloud SQL supports the standard isolation levels (READ COMMITTED, REPEATABLE READ, SERIALIZABLE); SERIALIZABLE pairs with optimistic concurrency control on the application side. Firestore reads come in three shapes:

    • single document get
    • query (where, order_by, limit)
    • listener (snapshot subscription)

    The listener path keeps a gRPC streaming RPC open and pushes updates as documents change; it is the right pattern for live dashboards and chat applications, and it counts against a different quota tier than batch reads. Writes come in four shapes:

    • single document set or update
    • transaction (read-modify-write with retry)
    • batched write (up to 500 operations)
    • bulk writer (parallelized batched writes with internal rate limiting)

    The transaction shape is the only one that gives strong read-modify-write semantics; batched writes are atomic across the batch but do not perform reads.

    // firestore_writes.go - the four Firestore write shapes
    package main
    
    import (
     "context"
     "cloud.google.com/go/firestore"
    )
    
    func singleWrite(ctx context.Context, c *firestore.Client, orderID string, total float64) error {
     _, err := c.Collection("orders").Doc(orderID).Set(ctx, map[string]any{
     "total": total,
     "state": "submitted",
     })
     return err
    }
    
    func transactionalUpdate(ctx context.Context, c *firestore.Client, orderID string, delta float64) error {
     return c.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
     ref := c.Collection("orders").Doc(orderID)
     snap, err := tx.Get(ref)
     if err != nil {
     return err
     }
     current, _ := snap.DataAt("total")
     return tx.Update(ref, []firestore.Update{
     {Path: "total", Value: current.(float64) + delta},
     })
     })
    }
    
    func batchedWrite(ctx context.Context, c *firestore.Client, ids []string) error {
     bw := c.Batch()
     for _, id := range ids {
     bw.Set(c.Collection("audit").Doc(id), map[string]any{"reviewed": true})
     }
     _, err := bw.Commit(ctx)
     return err
    }
    
    func bulkInsert(ctx context.Context, c *firestore.Client, docs []map[string]any) error {
     bw := c.BulkWriter(ctx)
     for i, d := range docs {
     bw.Set(c.Collection("ingest").Doc(d["id"].(string)), d)
     if i % 500 == 0 {
     bw.Flush()
     }
     }
     bw.End()
     return nil
    }
    

    Cloud Storage reads and writes split along streaming versus chunked lines.

    A streaming read returns a Reader that buffers a few MiB at a time and the application iterates; a download-to-bytes call buffers the whole object in memory and is the wrong shape for objects above a few megabytes.

    Writes have three shapes:

    • simple upload (single PUT for small objects)
    • resumable upload (chunked, with a session URI that survives client restarts)
    • streaming upload (a writable handle that flushes in the background)

    The Storage client library picks resumable for objects above approximately 8 MiB by default; on flaky networks the resumable threshold can be lowered to 1 MiB through the chunk_size option.

    # gcs_uploads.py - three Cloud Storage upload shapes
    from google.cloud import storage
    
    client = storage.Client()
    bucket = client.bucket("orders-archive")
    
    # Simple upload, single PUT, fine up to ~8 MiB
    def small_upload(blob_name: str, data: bytes) -> None:
     bucket.blob(blob_name).upload_from_string(data, content_type="application/json")
    
    # Resumable upload, chunked, survives client restarts
    def large_upload(blob_name: str, file_path: str) -> None:
     blob = bucket.blob(blob_name)
     blob.chunk_size = 8 * 1024 * 1024 # 8 MiB chunks
     blob.upload_from_filename(file_path)
    
    # Streaming upload, write side flushes asynchronously
    def stream_upload(blob_name: str, stream) -> None:
     blob = bucket.blob(blob_name)
     with blob.open("wb", chunk_size=4 * 1024 * 1024) as f:
     for chunk in stream:
     f.write(chunk)
    

    Cloud Storage object consistency is strongly consistent within a region (read-after-write, list-after-write, delete-after-delete) for object operations; replication across multi-region buckets is asynchronous.

    Object metadata operations (set-acl, set-iam-policy) are eventually consistent for cache propagation.

    Cloud Storage retention policies and Object Lifecycle Management from chapter 1 sit at the bucket layer and do not block writes that comply with the rule.

    💡 Exam Trap: Cloud Storage multi-region bucket consistency is the highest-frequency distractor for storage questions. Single-region buckets are strongly consistent for object reads after writes. Multi-region buckets are strongly consistent within the bucket for the operation that succeeded, but cross-region propagation is asynchronous; a read from a different region may return a stale version for a short window. Strong cross-region consistency means Spanner, not Cloud Storage multi-region.

    Firestore reads come with strong consistency within a single region (single-region mode) or strong consistency at the multi-region database level (multi-region mode).

    The same db.collection("x").doc("y").get() call returns the latest committed write across the database; what varies is the latency, with multi-region adding a 50 to 150 ms quorum cost.

    Firestore queries are strongly consistent and indexed; the index pattern (single-field index versus composite index) is the dominant performance lever, because a query without an index returns an error rather than a slow scan.

    🎯 Scenario: An order-management service on Cloud Run reads from Cloud SQL for PostgreSQL, writes audit events to Firestore, and stores invoice PDFs in Cloud Storage. Under load test, the team sees Cloud SQL errors of the form FATAL: remaining connection slots are reserved for non-replication superuser connections once concurrent traffic crosses 200 RPS. The Cloud Run service has --max-instances=200, concurrency 80, and a SQLAlchemy pool sized at 10 with overflow 5. That sets the worst-case slot count at 200 instances times 15 connections = 3,000 slots against an 8 vCPU instance with a 1,000 connection ceiling. The fix is either lowering the per-instance pool (to 4 with overflow 1) and raising concurrency to keep throughput, or sitting a PgBouncer-equivalent connection pool (such as pgbouncer packaged as a sidecar, or AlloyDB instead of Cloud SQL for built-in pooling).

    Publishing and consuming data from messaging services (Pub/Sub)

    Pub/Sub from inside an application service has two halves: publish and consume.

    The publisher client wraps a gRPC streaming endpoint and batches messages on three axes:

    • element count (default 100 messages)
    • byte size (default 1 MiB)
    • a flush-after-wait timer (default 10 ms)

    Tuning these is workload-specific.

    An order service that emits one event per request and runs at 50 RPS is bottlenecked on the wait timer.

    An ingest pipeline that emits thousands of events per second is bottlenecked on element count and byte size.

    The publisher client also exposes an enable_message_ordering flag, which assigns messages to ordering keys and guarantees in-order delivery to a subscriber that also has ordering enabled.

    # publisher.py - Pub/Sub publisher with batching and ordering
    from concurrent import futures
    from google.cloud import pubsub_v1
    from google.cloud.pubsub_v1.types import BatchSettings, PublisherOptions
    
    batch_settings = BatchSettings(
     max_messages=500,
     max_bytes=1024 * 1024, # 1 MiB
     max_latency=0.05, # 50 ms
    )
    
    publisher_options = PublisherOptions(enable_message_ordering=True)
    
    publisher = pubsub_v1.PublisherClient(
     batch_settings=batch_settings,
     publisher_options=publisher_options,
    )
    topic_path = publisher.topic_path("my-project", "orders")
    
    def publish_order(order_id: str, payload: bytes, region: str) -> None:
     future = publisher.publish(
     topic_path,
     payload,
     order_id=order_id,
     region=region,
     ordering_key=region, # serial delivery per region
     )
     future.result(timeout=30)
    

    Each publish() call returns a future; the application should wait on the future (or attach a callback) before acknowledging the upstream request, otherwise an in-process crash loses the message.

    The publisher client retries internally on retryable gRPC status codes (UNAVAILABLE, DEADLINE_EXCEEDED, INTERNAL); the application sees only the final outcome.

    For ordered publishing, a failure on one ordering key suspends future publishes on that key until resume_publish is called, which is the correct shape because retrying a failed message on the same key could otherwise reorder events.

    Consuming Pub/Sub from inside an application has two patterns: StreamingPull and synchronous Pull. StreamingPull is the default client behavior:

    • The subscriber opens a long-lived bidirectional gRPC stream.
    • Pub/Sub pushes messages over the stream.
    • The client acknowledges back over the same stream.

    This is the pattern for any long-running consumer process on GKE or a Compute Engine VM; it scales horizontally by adding more subscriber processes against the same subscription.

    Synchronous Pull (the pull() RPC) is the pattern for batch consumers that want explicit control: Scheduled jobs. Smaller workers. Consumers that want to bound the in-flight message count exactly.

    # subscriber.py - Pub/Sub StreamingPull subscriber with flow control
    from google.cloud import pubsub_v1
    from google.cloud.pubsub_v1.types import FlowControl
    
    subscriber = pubsub_v1.SubscriberClient()
    subscription_path = subscriber.subscription_path("my-project", "orders-worker")
    
    flow_control = FlowControl(max_messages=100, max_bytes=10 * 1024 * 1024)
    
    def handle(message):
     try:
     process_order(message.data, message.attributes)
     message.ack()
     except RecoverableError:
     message.nack() # redeliver after ack-deadline
     except FatalError:
     message.ack() # drop or route to dead-letter
    
    streaming_pull = subscriber.subscribe(
     subscription_path, callback=handle, flow_control=flow_control,
    )
    streaming_pull.result() # blocks the worker forever
    

    Push subscriptions, covered in chapter 3, target an HTTP endpoint (typically Cloud Run) with a CloudEvents payload and an OIDC token. From the consumer's point of view there is no client library at all, only an HTTP handler that returns 2xx for ack or non-2xx for nack.

    The dead-letter topic configuration (covered in chapter 3) is identical for push and for StreamingPull subscriptions: after --max-delivery-attempts failures the message is routed to a separate topic for offline analysis.

    💡 Exam Trap: Pub/Sub message ordering requires both the topic and the subscription to be in a single region, and requires enable_message_ordering=True on both sides. A globally distributed topic cannot offer ordered delivery; the exam tests this with stems describing global ingest from multiple regions and asking for in-order processing per customer. The right answer is a regional topic with ordering keys, not a global topic.

    💡 Exam Trap: StreamingPull and synchronous Pull are both pull subscriptions on the Pub/Sub server side; "push subscription" is a separate subscription type configured at create time. A stem describing "a subscription that pushes messages to a Cloud Run service" must use a push subscription; a stem describing "a worker that pulls messages on a long-lived stream" must use a pull subscription with StreamingPull (which is the default client behavior).

    ⚠️ Anti-Pattern: Calling future.result() on every publish() call synchronously, blocking the request thread. The publisher client is designed for fire-and-forget with batching; awaiting each publish individually defeats batching and limits throughput to one message per round trip. The correct pattern is to fan out a list of publishes, then wait() on the collected futures (or attach error callbacks).

    📊 Limit: Pub/Sub per-message payload maximum is 10 MB after base64 encoding. The default per-subscription StreamingPull throughput limit is 60 MB/s; raise it through quota requests or shard across subscriptions for higher fan-in. Ordering keys throttle to roughly 1 MB/s per key, so high-volume keys must be split.

    Decision Anchor: Choose Pub/Sub StreamingPull when the consumer is a long-running worker on GKE, Compute Engine, or any environment with stable process identity. Choose push subscriptions with Cloud Run when the consumer is HTTP-shaped and benefits from scale-to-zero. Choose synchronous Pull when the consumer is a scheduled batch job that wants explicit in-flight bounds. Choose Pub/Sub Lite when cost dominates and per-partition ordering is acceptable.

    Decision Tree: Picking a data-plane integration shape


    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.