Google PCD: Cloud-Native Application Architecture and Service Selection — Study Guide
Part of the Google Professional Cloud Developer — Study Guide. Practice with verified answers in the Google exam hub, or take timed practice tests on ExamRoll.io.
Overview
Cloud-native application architecture on Google Cloud centers on building stateless, resilient services that scale horizontally, minimize operational toil, and embrace managed services where appropriate. Effective service selection requires understanding trade-offs among control, portability, performance, cost, and operational responsibility. This section presents principles and patterns that help you design, modernize, and operate applications for global users with predictable reliability.
Cloud-Native Principles and Architecture Choices
Twelve-factor and stateless design
- Codebase, dependencies, and build-release-run: Pin exact dependencies, create immutable artifacts, and separate build from release. Container images and Cloud Build pipelines enforce reproducible releases.
- Config in the environment: Externalize configuration using environment variables, Secret Manager, Kubernetes Secrets, or instance metadata for Compute Engine. Do not bake credentials or per-deployment settings into images. For Compute Engine managed instance groups, use instance template metadata for per-deployment values.
- Backing services: Treat databases, queues, and caches as attached resources. Prefer managed services (Cloud SQL, Cloud Spanner, Firestore, Memorystore, Pub/Sub) to reduce operational burden.
- Stateless processes: Scale by adding instances; store session state externally (Memorystore for Redis, Firestore, or Spanner). Write logs to stdout/stderr or log files collected by the Cloud Logging agent.
- Disposability: Fast startup/shutdown enables rapid scaling and rolling updates. Handle SIGTERM for graceful shutdown.
- Logs as event streams: Emit structured logs; use Cloud Logging for ingestion and Cloud Monitoring for alerting.
Architecture trade-offs
- Monolith
- Pros: Simplified dev/test, fewer network boundaries, single deployment unit.
- Cons: Slower independent delivery, scale constraints, tight coupling across domains.
- Failure modes: One hot path can consume shared resources; regressions impact all features.
- Modular monolith
- Pros: Clear internal module boundaries, refactoring path to services, single deployable.
- Cons: Still constrained by monolithic deployment and database.
- Use for teams maturing domain boundaries before extracting services.
- Microservices
- Pros: Independent deployability, targeted scaling, team autonomy, failure isolation with proper bulkheads.
- Cons: Distributed systems complexity, consistency, observability, and operational overhead.
- Failure modes: Cascading failures via synchronous calls; schema drift; chatty networks.
- Event-driven
- Pros: Loose coupling, async resilience, natural buffering, auditability via logs/streams.
- Cons: Debugging complexity, eventual consistency, ordering and exactly-once semantics are hard.
- Pub/Sub provides at-least-once delivery; design idempotent consumers.
- Serverless (Cloud Run, Cloud Functions, App Engine)
- Pros: Minimal ops, scale to zero, per-request autoscaling, integrated security and telemetry.
- Cons: Execution time and concurrency limits, cold starts, platform-specific constraints.
- Use for bursty workloads, mobile/web backends, and event processing.
- Monolith
Communication Patterns and Service Selection
Synchronous vs asynchronous calls
- Synchronous
- Use for request/response APIs requiring immediate results.
- Protocols: gRPC (HTTP/2, streaming, compact Protobuf; excellent for mobile bandwidth and strong contracts), HTTP/JSON (broad compatibility; simpler debugging).
- Risks: Tight coupling and latency amplification; use timeouts, retries with jitter, and circuit breakers.
- Asynchronous
- Use Pub/Sub or Cloud Tasks when work can be deferred or batched.
- Benefits: Smooths spikes, isolates failures, improves user-perceived latency via eventual completion.
- Risks: Requires idempotency and compensating actions; visibility into in-flight work must be built.
- Synchronous
Service selection criteria on Google Cloud
- Control and portability
- Compute Engine: Full VM control and custom images; higher ops burden.
- GKE: Portable containers and service mesh options; robust autoscaling; shared responsibility.
- Cloud Run: High portability for containers with minimal ops; scale-to-zero; request-oriented.
- App Engine: Opinionated PaaS with built-in routing and scaling; fastest path for certain languages.
- Scale and latency
- Global HTTP(S) Load Balancing with Cloud CDN for edge acceleration.
- Datastores:
- Cloud Spanner: Global consistency, horizontal scale, multi-region 99.999% availability.
- Cloud SQL: Managed relational DB, regional, read replicas including cross-region.
- Firestore: Document DB with global availability in multi-region, strong consistency for single documents.
- Cloud Bigtable: Low-latency, massive scale for wide-column use cases.
- Memorystore: Low-latency cache for hot paths and sessions.
- Operational responsibility
- Prefer managed services for core concerns (availability, patching, backups, upgrades).
- Self-managed offers flexibility but adds toil and failure surface (e.g., self-hosted Kafka vs Pub/Sub).
- Data movement and integration
- Use VPC-native connectivity, Private Service Connect, and internal HTTP(S) Load Balancing for low-latency, private access.
- Service discovery: Kubernetes Service names within a cluster; Compute Engine internal DNS for VMs.
- Control and portability
Kubernetes Service example (in-cluster name discovery): apiVersion: v1 kind: Service metadata: name: image-resize spec: selector: app: image-resize ports:
- port: 80 targetPort: 8080 type: ClusterIP
Boundaries, Compatibility, and Reliability Patterns
Domain boundaries and ownership
- Use domain-driven design to define bounded contexts. Each service owns its data and publishes APIs/events as contracts.
- Avoid shared databases across services; use well-defined interfaces and event propagation.
- Ownership implies on-call, SLOs, release cadence, and budget accountability per service.
API contracts and backward compatibility
- Version APIs explicitly (e.g., v1 in path or header). Prefer additive changes; avoid breaking fields or behaviors.
- Use consumer-driven contract tests and canary releases. Deprecate with timelines and telemetry on usage.
- For mobile clients, expect long tail versions; maintain multiple API versions concurrently.
Failure isolation and resilience
- Bulkheads: Isolate resources by service or priority class (separate node pools, instance groups, quotas). Prevent a best-effort feature from starving critical paths.
- Circuit breakers: Trip after consecutive failures to a dependency; shed load and allow recovery window. Implement via service mesh (e.g., Envoy), gateway policies, or libraries.
- Timeouts and retries: Use truncated exponential backoff with jitter; ensure idempotent handlers.
- Graceful degradation: Omit noncritical UI components on timeouts; serve cached or approximate data rather than errors.
- Health checks and readiness probes: Only route traffic to ready instances; use liveness for self-healing.
Example truncated exponential backoff (HTTP 429): retry = 0 max_retry = 5 base = 0.5 while retry < max_retry: resp = fetch_gcs_object() if resp.status_code == 200: break if resp.status_code in (429, 500, 503): sleep = min(8, base * (2 ** retry)) + random.uniform(0, 0.25) time.sleep(sleep) retry += 1 else: raise Exception(“Non-retryable error”)
Global and Operational Considerations
Multi-region patterns for global users
- Global front end: Use global external HTTP(S) Load Balancing with anycast IP and Cloud CDN for static content. Configure negative caching and validation to reduce origin load.
- Data plane:
- For 5-nines database availability and minimized global read latency, use a multi-regional Cloud Spanner instance (e.g., nam-asia-eur1) and provision sufficient nodes for compute and quorum (minimum three nodes for production).
- For read-heavy patterns without strict global consistency, consider regional primary with cross-region read replicas; accept higher write latency across continents.
- Application plane:
- Deploy stateless services in multiple regions with autoscaling (GKE or Cloud Run). Use backend services and network endpoint groups per region.
- Route by latency while honoring data residency and compliance constraints.
- Caches: Place Memorystore or edge caches close to users to absorb read traffic and protect origins.
Managed vs self-managed
- Use Cloud Monitoring for metrics, Cloud Logging for logs, Cloud Trace/Profiler for latency and CPU/memory hotspots. Create alerting policies for SLO burn rates and uptime checks for external availability.
- If an existing observability platform must remain the system of record, ingest with Cloud Logging first for low-latency alerts, then export via sinks to the external platform.
Modernization and incremental migration
- Strangler pattern: Front the monolith with a gateway; route specific endpoints to new services. Gradually replace capabilities.
- Branch by abstraction: Introduce an interface around a dependency and swap implementation behind it (e.g., database or storage).
- Anti-corruption layer: Translate between legacy data models and new bounded contexts.
- Data migration: Use dual writes with verification or event sourcing to backfill; plan cutovers with backpressure controls.
- Phased delivery: Replace features in stages to minimize business risk; continuously measure SLOs.
Design reviews and trade-off evaluations
- Security: Threat model, IAM least privilege, service accounts instead of embedded keys (use Application Default Credentials on GCE/GKE/Cloud Run), CMEK where required, private connectivity, WAF and rate limits, vulnerability and web security scanning.
- Reliability: Define SLOs and error budgets, multi-region failover plans, capacity headroom, chaos drills, dependency maps.
- Performance: Tail latency analysis, load testing at the edge and origin, connection reuse (HTTP/2, gRPC), compression, caching strategy.
- Cost: Right-size resources, autoscaling policies, committed use discounts, scale-to-zero for bursty workloads, egress and CDN offload.
- Operations: Runbooks, rollbacks, progressive delivery (canary, blue/green), policy as code, backups and DR tests, incident response integration.
Practical Problem Scenario
Nimbus Retail is launching a global e-commerce platform with personalized images, strict latency targets under 200 ms at p95 worldwide, and a 99.999% availability requirement for the order database. They also must keep their existing SIEM while improving alerting speed.
- Establish a global, highly available database using Cloud Spanner
- Action: Create a multi-regional Spanner instance in nam-asia-eur1 with at least three nodes and split tables into appropriate interleaved schemas for locality.
- Rationale: Multi-regional Spanner delivers 5-nines and low read latency via replicas on three continents; three or more nodes ensure sufficient compute and replica quorum capacity.
Example:
gcloud spanner instances create nimbus-orders
–config=nam-asia-eur1 –description=“Global orders” –nodes=3
- Frontend and API global deployment
- Action: Use global external HTTP(S) Load Balancing with Cloud CDN for static assets and dynamic routing to regional backends (GKE services in us-central1, europe-west1, asia-east1).
- Rationale: Anycast VIP minimizes RTT; CDN caches images near users; backend services distribute requests to the nearest healthy region.
- Stateless services on GKE with in-cluster discovery
- Action: Deploy image-resize and API services on GKE with horizontal pod autoscaling and ClusterIP Services for in-cluster name-based access; expose public endpoints via an Ingress.
- Rationale: Stateless pods allow elastic scaling; Kubernetes Service abstracts pod IPs and provides stable DNS, reducing client coupling.
- Event-driven image processing
- Action: Publish image-processing tasks to Pub/Sub; run Cloud Run services subscribed via push to process objects stored in Cloud Storage. Implement truncated exponential backoff with jitter on GCS 429/5xx.
- Rationale: Pub/Sub buffers spikes and isolates failures; Cloud Run scales per-message; backoff reduces error amplification and helps buckets warm up gradually.
- Observability and rapid alerting
- Action: Use Cloud Logging and Cloud Monitoring to ingest logs and metrics, define uptime checks for APIs, and create alerting policies on error rates and latency. Configure a log sink to export to the existing SIEM.
- Rationale: Native telemetry provides low-latency alerts and managed uptime checks; export preserves the centralized SIEM without sacrificing alert speed.
- Externalized configuration and secrets
- Action: Store nonsecret config in ConfigMaps; secrets and API keys in Secret Manager with Workload Identity for GKE. For any Compute Engine-based jobs, use instance metadata for per-deployment values.
- Rationale: Externalized config enables immutable images and environment-specific settings; avoids embedding secrets; metadata supports VM variance without code changes.
- Failure isolation and graceful degradation
- Action: Apply bulkheads with separate node pools for best-effort personalization workloads; enforce request budgets and circuit breakers for personalization services. In the UI, omit noncritical widgets on dependency timeouts.
- Rationale: Isolating capacity prevents best-effort features from starving checkout; circuit breakers limit blast radius; graceful degradation preserves core journeys.
- API contracts and compatibility
- Action: Define gRPC contracts for mobile clients (v1) with HTTP/JSON transcoding for web; adopt additive changes and maintain at least two versions during mobile rollout.
- Rationale: gRPC reduces bandwidth and provides strong typing; transcoding eases browser and partner integration; versioning preserves backward compatibility.
- Security and identity
- Action: Use per-service Google service accounts with least-privilege IAM; rely on Application Default Credentials. Enable Cloud Armor for edge protections and enforce TLS everywhere.
- Rationale: Workload identity removes key management risks; WAF and rate limits mitigate abuse; encryption in transit is default and mandatory.
- Continuous delivery and release safety
- Action: Implement canary releases with percentage-based traffic splitting at the load balancer and automatic rollback on SLO burn alerts. Keep blue/green environments per region.
- Rationale: Progressive delivery limits risk; regional blue/green speeds rollback and enables safe schema migrations aligned with versioned APIs.
All domains · Compute →
Practice these questions → · Timed practice on ExamRoll.io →
Pass the whole exam — not just this question
You found this answer. Get every verified question and explanation in one place, and save hours of prep. Free to start.
Pass your exam →