Professional Cloud Developer Cheatsheet
Google Cloud Professional Cloud Developer
Download free PDFDesigning highly scalable, secure, and reliable cloud-native applications (32%)
Compute and modernization
- **Cloud Run** suits stateless HTTP and gRPC containers with variable traffic. **GKE** provides Kubernetes workload and networking control. **Compute Engine** preserves OS access and VM dependencies.
- **App Engine standard** provides managed runtimes and scaling. Flexible uses VM-backed instances and custom runtimes. Choose by runtime compatibility, startup behavior and operational needs.
- Decompose a monolith in **small, independently testable steps**. Start with a bounded capability with few dependencies; preserve API contracts and rollback paths during migration.
- Keep services **stateless** and put durable state in managed storage. Use the same immutable application artifact across environments, with configuration supplied separately.
Availability, geography and capacity
- **Zones** isolate local infrastructure failures; **regions** separate larger failure domains. A regional GKE control plane and replicas spread across zones improve zonal resilience.
- **Global deployment** requires compute placement, traffic routing and data replication to work together. Read replicas reduce eligible read latency; they do not remove write coordination latency.
- Define **RTO** for recovery time and **RPO** for acceptable data loss. High availability, backups and disaster recovery address different failure and recovery requirements.
- Keep **data residency** consistent across databases, buckets, logs, backups and processing. A multi-region location does not imply storage within one required country.
API contracts and communication
- **REST** exposes resources using HTTP semantics. **gRPC** uses typed Protocol Buffers and HTTP/2, supporting compact messages and streaming. Match client support and connection duration to the platform.
- Use **synchronous calls** when the caller needs a committed result immediately, such as a seat reservation. Use asynchronous messaging when durable acceptance and later processing meet the requirement.
- Publish an explicit **API contract**. Make additive changes compatible with existing clients; route breaking changes through separate API versions and retire them deliberately.
- **Timeouts**, circuit breakers and bounded concurrency contain slow dependencies. Run independent calls in parallel; let optional UI content fail without blocking the rest of the page.
- **CORS** controls browser access across origins. Allow the exact trusted origin and handle preflight requests; CORS does not authenticate callers or restrict non-browser clients.
Data platform selection
- **Cloud SQL** manages familiar relational engines. Configure HA, backups and connection capacity explicitly. **AlloyDB** serves PostgreSQL-compatible workloads needing its performance and availability architecture.
- **Spanner** combines relational transactions with distributed scale and strong consistency. Choose replica geography for latency and resilience; retain schema and capacity planning responsibilities.
- **Firestore** stores flexible documents and supports mobile synchronization, offline caching and real-time listeners. **Bigtable** serves high-throughput key and range access to wide-column data.
- **Firestore Native mode** supports mobile/web SDKs and security rules; Datastore mode uses Datastore APIs and its entity model. Server client libraries use IAM rather than mobile security rules.
- **Cloud Storage** holds objects such as images, videos and exports. **BigQuery** runs analytical SQL over large datasets. Keep heavy analytics separate from operational transaction processing.
- **Memorystore** provides low-latency caching. Use Redis sorted sets for ranked leaderboards; keep durable profiles, carts and transaction records in a persistent database.
Schema, indexes and consistency
- Design **Bigtable row keys** for query prefixes and distributed writes. A customer prefix followed by an event component can group related events; a leading sequential timestamp can create a write hotspot.
- Distribute **Spanner primary keys** to avoid concentrating writes. Prefer well-distributed identifiers over monotonically increasing leading keys; add indexes for required lookup paths.
- Store growing **Firestore lists** as separate documents in collections or subcollections. Avoid unbounded arrays on a parent document; paginate query results with limits and cursors.
- Use **transactions** for read-modify-write operations such as balances and reservations. Retry transaction conflicts safely and keep external side effects out of retryable transaction callbacks.
- **Strong reads** provide current committed data. **Stale reads** trade freshness for eligible latency benefits. Replication and routing modes can change guarantees; choose them for the application's consistency needs.
- **Cloud Storage** provides strong consistency for object operations and listings. **Bigtable** offers atomic single-row operations; replicated multi-cluster reads can observe stale data and do not provide relational joins.
- Normalize repeated values into child rows when independent indexing is needed. In SQL, **UNION** removes duplicate rows; **UNION ALL** preserves them; **JOIN** combines matching columns across rows.
Cache and session design
- Use **cache-aside**: read the cache, fall back to the authoritative store on a miss, then populate the cache. Set TTLs and invalidation rules to control staleness.
- Separate short-lived **sessions** from durable shopping carts. Key persistent carts by authenticated user ID so that users can resume across devices and sessions.
- Plan for **cache failure** with bounded retries, backoff and jitter. Serve stale data only when acceptable; prevent a cache outage from overwhelming the backing database.
- **Read replicas** scale eligible Redis reads; HA and failover configuration address availability. Replication lag can make replica reads stale, and client reconnection still matters.
Identity and least privilege
- **Authentication** establishes identity; **authorization** permits an action. Bind roles to groups or service accounts at the narrowest useful resource scope.
- Assign a dedicated **runtime service account** to each workload. **Application Default Credentials (ADC)** lets supported libraries obtain its short-lived credentials without distributing key files.
- For **cross-project access**, grant the runtime principal permissions on the destination resource. Granting access to the human deployer does not grant access to the running application.
- **Workload Identity Federation for GKE** gives Kubernetes workloads scoped Google Cloud access. Use the workload's Kubernetes service account instead of sharing node credentials or JSON keys.
- **Workload identity federation** supports external workloads; **workforce identity federation** supports external human users. Service-account impersonation provides short-lived access for authorized development and automation.
- A deployer may need **iam.serviceAccounts.actAs** to attach a runtime identity. **Service Account Token Creator** supports token creation and impersonation; these are distinct permissions.
User and service authentication
- Use **OAuth 2.0 authorization code flow** for delegated access: redirect to consent, receive a code, exchange it for tokens, then call the API with the access token. Request minimal scopes.
- **API keys** identify calling applications for quotas and reporting; they do not replace user authentication. Validate identity tokens and required claims when authenticating users or services.
- For a private **Cloud Run** endpoint, grant the caller the invoker role and send an ID token with the expected audience. Network ingress restrictions and IAM authorization must both permit the request.
- **Identity-Aware Proxy (IAP)** gates supported web applications using user and group access. Validate IAP assertions when required, and prevent direct access that bypasses the protected entry point.
- **HTTPS** encrypts transport. **Cloud Armor** adds supported edge WAF and DDoS protections. API authentication, input validation and parameterized queries remain separate application controls.
Secrets, encryption and protection
- Store passwords and API credentials in **Secret Manager**; grant secret access only to the runtime identity. **Cloud KMS** manages encryption keys rather than serving as a general password store.
- Rotate secrets with **overlapping valid credentials**: publish the new version, allow clients to refresh, then revoke the old credential after the cache and rollout window.
- **Customer-managed encryption keys (CMEK)** use KMS; separate key administration from key use. A **customer-supplied encryption key** must be provided correctly for relevant object operations.
- Kubernetes Secret values encoded in **base64** are not encrypted by that encoding. Use tight RBAC, supported encryption controls and managed secret delivery; avoid credentials in images or repositories.
- **VPC Service Controls** adds a service perimeter against data exfiltration. It complements IAM and private connectivity. De-identify sensitive analytics data and minimize collection and logging of PII.
Object access and lifecycle
- Use a **signed URL** for time-limited access to a specific object and HTTP method. It is a bearer credential: anyone possessing it can use its permitted action until expiration.
- Let clients **upload directly to Cloud Storage** using authorized signed requests or resumable uploads. Avoid routing large payloads through an application server solely to store them.
- **Uniform bucket-level access** centralizes access through IAM; **public access prevention** blocks public grants. Avoid making a private bucket public to simplify application access.
- A **retention policy** prevents deletion or replacement during the retention period; locking it makes the policy irreversible. **Object Versioning** preserves generations, and lifecycle rules manage aging or deletion.
- Choose **Standard, Nearline, Coldline or Archive** by access frequency and total retrieval costs. Lifecycle transitions and TTL cleanup are asynchronous; use explicit deletion when completion must be confirmed immediately.
- In a **flat namespace**, slashes are part of object names and prefixes simulate directories. Use metadata-only requests and partial response fields when object bytes are unnecessary.
Building and testing applications (23%)
Developer environments and access
- **Cloud Shell** provides browser-based tools without keeping source on the local computer. **Cloud Workstations** provides controlled development environments with VPC access and centrally maintained images.
- **Cloud Code** integrates cloud development into supported IDEs. **Skaffold** automates build/deploy iteration; a local Kubernetes environment such as Minikube can exercise manifests before cloud deployment.
- Use **gcloud container clusters get-credentials** to configure cluster access and **kubectl config use-context** to switch contexts. Each developer should authenticate with their own identity.
- Separate **gcloud CLI credentials** from local **ADC** used by application libraries. Prefer approved impersonation or federation when local automation must run as a service account.
- Use official documentation for **disk and service tradeoffs**. AI assistants can accelerate exploration; verify generated commands, security changes and platform claims before using them.
Local tests and emulators
- **Unit tests** isolate business logic with mocks or fakes. **Integration tests** exercise service interactions. End-to-end tests validate complete user flows and contracts.
- Use supported **Pub/Sub, Firestore, Bigtable or Spanner emulators** for local functional tests. Configure the client to use the emulator endpoint; **PUBSUB_EMULATOR_HOST** selects the local Pub/Sub endpoint.
- Feed tests **deterministic synthetic fixtures**, including duplicate, invalid and out-of-order events. Keep production-sensitive data and test messages out of production workflows.
- Use the **Functions Framework** to run function handlers locally and send representative HTTP or CloudEvent payloads. Test event parsing and business logic independently.
- Emulators do not reproduce every **IAM, networking, quota or performance** behavior. Use isolated real cloud resources for production-like integration and performance verification.
Cloud Build mechanics
- **Cloud Build** executes containerized steps from a build configuration. Use distinct build, unit-test, integration-test and deployment steps so failures identify the failed stage.
- A nonzero **step exit code** should stop the pipeline before deployment. Grant deployment rights to the pipeline identity and restrict paths that would bypass its required tests.
- **/workspace** persists files between steps in one build. Additional named volumes can share other paths; a builder's unrelated container filesystem does not persist automatically.
- Package missing tools in a **custom builder image**. Pin dependencies and builder versions so builds remain reproducible, and keep credentials out of the image.
- Trigger CI from **commits or pull requests** for early feedback. Use release tag patterns for controlled releases and short-lived branches with frequent merges to the main branch.
Container construction and build speed
- Package independently operated components in **separate containers**. Use a clear foreground process, a small trusted base image and only the dependencies required at runtime.
- Put stable dependency installation before frequently changing source in the **Dockerfile**. Use **multi-stage builds** to keep compilers and build tools out of the final runtime image.
- Reuse Docker layers with an explicitly available **cache source**, such as **--cache-from**. Rebuild invalidated layers correctly; cache reuse must not hide dependency or security updates.
- **Buildpacks** can create images from supported source without a Dockerfile. **Jib** builds Java container images from application source and dependencies.
- Increase build machine capacity when the build is **CPU-bound**; measure first. A private worker pool solves network and isolation requirements rather than automatically making every build faster.
Artifacts and supply chain
- **Artifact Registry** stores container images and other supported packages. Push the image before a deployment step that needs to pull it; grant writer and reader rights to the correct identities.
- Use **image digests** for exact artifact identity. Version tags aid release discovery, but mutable tags such as latest are unsuitable as the sole record of what was tested or deployed.
- **Artifact Analysis** reports known vulnerabilities. **Binary Authorization** enforces deployment policy using trusted attestations; scanning alone does not block a deployment.
- After required tests and scans pass, create an **attestation bound to the image digest**. Scope production admission policies to the intended clusters or services and protect the attestor's signing key.
- **Build provenance** records how an artifact was produced. Keep provenance, security findings and policy decisions available to the release pipeline; a build record alone does not prove an image is safe.
Performance and resilience testing
- Use a distributed framework such as **JMeter or Locust** to generate controlled concurrent load. Scale load generators independently and verify they are not the bottleneck.
- Measure **latency percentiles, throughput, errors and saturation** during spikes, sustained load and scale-down. Trace dependencies to identify slow database calls or downstream services.
- Isolate concurrent performance runs with **separate cloud resources and test data**. Shared test state can invalidate results; emulator timing is not a capacity benchmark.
- **Chaos engineering** injects controlled failures to verify recovery and containment. Load tests, unit tests and chaos tests examine different risks.
- **Web Security Scanner** examines supported deployed web applications for classes of web vulnerabilities. Image dependency scanning addresses a different layer of the stack.
Configuring cloud-native applications for deployment (24%)
Cloud Run services, functions and jobs
- A **Cloud Run service** exposes a request endpoint; a **Cloud Run job** executes tasks to completion. Functions provide handler-focused development for HTTP or event-driven workloads.
- **gcloud run deploy --source** builds supported source using managed build tooling. An image deployment uses a previously built image in a registry.
- Listen on the configured **PORT** on all required interfaces and handle concurrent requests safely. Keep startup fast; initialize reusable clients once and avoid unnecessary startup dependency calls.
- Set **minimum instances** for reduced cold-start exposure and **maximum instances** to bound scaling. Tune concurrency, CPU and memory together with downstream capacity and connection limits.
- Treat the container's writable filesystem as **ephemeral**. Bound files and buffers; persist durable data externally. Offload durable background work to queues or jobs instead of relying on execution after the response.
Release strategies and traffic control
- **Rolling updates** gradually replace replicas. **Canary releases** expose a small share of live traffic first and expand only when latency and error signals remain acceptable.
- **Blue/green** keeps separate old and new deployments for a traffic switch and rapid reversal. Keep database schema changes compatible with both during the rollback window.
- **A/B testing** compares stable user cohorts against business metrics. **Feature flags** target selected customers or disable a risky feature independently of image deployment.
- **Traffic mirroring** sends copies of requests to a shadow deployment without using its responses. Suppress or isolate side effects so mirrored requests do not create real orders or payments.
- In Cloud Run, deploy a **revision with no traffic**, test its tagged URL, then allocate traffic gradually. Route traffic back to a known-good revision when release criteria fail.
- **Header-based routing** can select cohorts such as user-agent groups. Weighted traffic splitting chooses proportions; it does not inherently identify registered test customers.
Kubernetes workload and storage objects
- A **Deployment** maintains stateless replicas through ReplicaSets. A **StatefulSet** adds stable identities and per-replica storage. A **DaemonSet** runs node-level agents on eligible nodes.
- A **Service** gives a stable virtual endpoint over changing Pod addresses. Use **ClusterIP** and service DNS for callers inside the cluster; do not hard-code Pod IPs.
- A **PersistentVolumeClaim (PVC)** requests storage; a **PersistentVolume (PV)** represents supplied storage. Choose access modes and drivers appropriate to concurrent readers and writers.
- Use **Filestore/NFS** for applications requiring a shared writable filesystem. Object-storage FUSE has different semantics and performance from a general-purpose POSIX filesystem.
- For supported **volume expansion**, enable it in the StorageClass and increase the PVC request. Verify controller and filesystem expansion; growing the underlying disk alone is insufficient.
- Use **ConfigMaps** for nonsecret configuration and managed secrets for credentials. Use an init container for required startup preparation and readiness to withhold traffic until ready.
Health checks and graceful shutdown
- **Readiness probes** decide whether a Pod should receive Service traffic. **Liveness probes** restart a stuck container; avoid tying liveness to a shared dependency outage that could restart every replica.
- A **startup probe** protects slow initialization from premature liveness failures. Tune probe thresholds from measured startup and response times rather than masking persistent failures.
- Handle **SIGTERM**: stop accepting work, drain in-flight requests, close database connections, and exit within the termination grace period. A **preStop** hook consumes part of that same period.
- For a Deployment, **maxSurge** allows extra Pods and **maxUnavailable** permits unavailable replicas. A surge of one with zero unavailable preserves old capacity while a healthy replacement starts.
- A **PodDisruptionBudget** limits eligible voluntary disruptions such as drains. Its minAvailable is the capacity to keep; it is not a substitute for Deployment rollout settings or protection against zone failure.
Autoscaling, isolation and scheduling
- **Horizontal Pod Autoscaler (HPA)** changes replica count. **Vertical Pod Autoscaler (VPA)** adjusts resource recommendations or requests. **Cluster autoscaler** supplies nodes for schedulable pending Pods.
- Use **CPU or memory metrics** for resource-driven scaling and an **external metric**, such as subscription backlog, for queue consumers. Resource utilization targets depend on meaningful resource requests.
- **Requests** guide scheduling and reservations; **limits** constrain usage. CPU limits can throttle execution, while exceeding a memory limit can terminate a container.
- Combine **namespaces, RBAC, ResourceQuota and LimitRange** for team boundaries and resource control. Namespaces alone do not isolate network traffic or hostile tenants.
- Use **NetworkPolicy** for supported L3/L4 traffic controls and topology spread for replica placement. A mesh authorization policy can restrict HTTP paths; network policy does not inspect URL paths.
- In **Autopilot**, select supported compute classes and architecture in workload configuration. Build compatible multi-architecture images; use **Spot Pods** only for interruption-tolerant workloads.
Routing and service networking
- **Ingress or Gateway** configures supported application load balancing. Host and path rules can route multiple APIs or domains through a shared entry point; a LoadBalancer Service exposes a different service abstraction.
- An **Application Load Balancer** supports HTTP-aware routing and managed TLS certificates. DNS maps custom hostnames to the entry point; an A record or CNAME alone does not configure TLS or backend routing.
- Permit the correct **health-check and proxy traffic** to backends. Check target tags, ports, paths and firewall direction; backend health checks and user-visible uptime checks serve different purposes.
- **Cloud CDN** caches eligible content near users and can serve Cloud Storage backend buckets. Set appropriate cache-control and authorization behavior for private or personalized responses.
- **Cloud Service Mesh** supports service traffic policy, observability and mTLS. Proxy-based REST traffic and proxyless gRPC have different configuration requirements; a control plane is not the application data path.
Automated delivery and VM operations
- Store application and **Terraform infrastructure definitions** in Git. Build once, test, then promote the same artifact through development, test and production with environment-specific configuration.
- **Cloud Deploy** manages releases, targets and rollouts. Use supported promotion automation or deployment events to advance only after the previous target succeeds, with approval gates where required.
- A **private Cloud Build worker pool** can access required private resources. Combine supported service perimeters, restricted egress and admission policies to protect source and artifacts.
- For **managed instance groups**, create a new immutable instance template and use rolling update budgets plus health validation. Extra surge capacity increases resource usage; zero surge requires an availability tradeoff.
- Supply VM **nonsecret configuration through metadata** and retrieve it from the metadata server. Use Secret Manager for credentials. Startup scripts initialize an instance; shutdown scripts should drain work promptly.
- Diagnose failed VM boots with **serial output**, disk space and filesystem checks. Use **IAP TCP forwarding** for supported private VM administration instead of exposing SSH broadly.
Integrating applications with Google Cloud services (21%)
Client libraries, calls and error handling
- Prefer supported **Cloud Client Libraries** for idiomatic APIs, credential discovery and retry behavior. Enable the required service APIs in the relevant projects before diagnosing application permissions.
- Batch small operations where supported, request only required **fields**, and paginate large result sets. Reuse clients and bounded connection pools instead of recreating them per request.
- Use bounded **exponential backoff with jitter** for retryable throttling and transient failures. Respect deadlines and retry hints; check library retries before adding another retry loop.
- Retry writes only when **idempotency** is guaranteed or duplicates can be detected. Use idempotency keys, conditional writes or storage generation preconditions for operations that might already have succeeded.
- A **403** requires identity, resource permissions and policy investigation; a network timeout suggests a different layer. For **429**, examine quota, hotspots and request rate, reduce avoidable calls and ramp new load gradually.
- Use **gcloud storage cp** for file/object transfer, **gcloud compute scp --recurse** for VM directory copies, and CLI **--filter** to select management results. Separate control-plane APIs from database data queries.
Cloud SQL and private database connectivity
- **Cloud SQL Auth Proxy** and language connectors provide authenticated, encrypted connections; grant **Cloud SQL Client** to the runtime principal. Database users and SQL privileges still control data operations.
- A proxy or connector does not create a **network path** to a private IP. Establish supported VPC routing or private connectivity and select the private endpoint explicitly where needed.
- **Direct VPC egress** or a supported **Serverless VPC Access connector** connects serverless workloads to VPC resources. Check region alignment, egress rules, DNS and destination reachability.
- **Private Google Access** lets eligible resources without external IPs reach Google APIs. **Private Service Connect** provides private consumer endpoints for supported services; it differs from VPC peering and private services access.
- Plan **cross-project database access** with resource IAM, API enablement and network connectivity. Peering is not transitive; an auth proxy does not bypass isolated networks.
- Bound each instance's **database connection pool** and total autoscaled connections. Reuse connections and apply idle and acquisition timeouts; raising frontend scale can exhaust the database.
Pub/Sub topology and durable processing
- Publishers send to a **topic**; each **subscription** receives its own copy. Independent downstream systems need separate subscriptions, while replicas sharing one subscription divide its work.
- **Pull** subscribers control retrieval and flow; **push** delivers to an endpoint and fits request-driven services. Configure service authentication and the endpoint's invoker permissions for authenticated push.
- With **at-least-once delivery**, messages may repeat. Commit the side effect before acknowledging, use idempotent processing and extend acknowledgment deadlines for legitimate long-running work.
- An **ordering key** groups ordered messages within supported publishing and subscription conditions. It does not create global ordering or sort events by their business timestamp; reject stale updates when freshness matters.
- **Exactly-once delivery** is an optional supported pull-subscription capability with defined regional behavior. It does not make arbitrary external side effects atomic; database deduplication or transactions may still be needed.
- Use **dead-letter topics**, retry policies and backlog monitoring for poison messages and slow consumers. On shutdown, stop pulling, finish or release outstanding messages, then close connections.
Events, scheduling and orchestration
- **Eventarc** routes supported events to services or workflows. Use object events for file processing and audit-log events for management operations such as bucket or VM creation.
- Configure event **type, resource and location filters** to match the provider's supported schema. Filter object identity in the handler when the trigger cannot express the required filename condition.
- **Cloud Storage Pub/Sub notifications** publish supported object events without an extra application relay. Event-driven handlers must tolerate repeated events and avoid triggering themselves indefinitely.
- **Workflows** orchestrates service calls using outputs, conditions, retries and parallel branches. Use connectors, including the Cloud Run Admin API connector, to execute supported jobs.
- **Cloud Tasks** dispatches controlled work to a chosen endpoint; **Cloud Scheduler** starts scheduled work. Use an appropriate service identity and token audience, and verify ingress as well as IAM.
- Use **Pub/Sub fanout** for independent reactions such as notifications and analytics. Use an orchestrator when steps depend on earlier outputs; **Dataflow** processes batch or streaming data, while **Composer** runs Airflow orchestration.
API management and service discovery
- **Apigee** applies API policies, client identification, authentication and analytics. **API Gateway** provides managed API front doors from API definitions; keep backend authorization consistent with the selected gateway.
- **Quota** enforces an allowed request count over a period; **SpikeArrest** smooths bursts. Use customer or application identifiers for tier limits. Asynchronous distributed quota enforcement can trade strictness for speed.
- In Apigee, **environment groups** associate hostnames with environments. Separate hostnames and groups when test and production must expose different API deployments.
- **TargetServers** describe backend destinations. Regional routing can choose the appropriate local backend using runtime region context; equal load-balancing weights do not imply geographic affinity.
- Use **Apigee API Analytics** and appropriate viewer access to inspect API traffic. **Service Directory** registers and discovers endpoints; it is not a substitute for authentication or traffic load balancing.
Data ingestion and storage access
- **BigQuery** supports batch jobs for delay-tolerant analytics. Grant permission to create jobs in the execution project and separate read permission on the source datasets.
- Use **authorized views or row-level controls** to expose only permitted data. Locate datasets according to residency requirements and use appropriate DML operations for targeted record deletion.
- Batch ingestion or the **Storage Write API** avoids one-request-per-small-row overhead. Application-created committed streams with managed offsets support exactly-once writes within a stream; the default stream does not provide that guarantee.
- **Datastream** can replicate supported operational database changes into BigQuery for analytics. Avoid repeatedly running heavy warehouse-style reports against the production transaction database.
- **Dataproc** runs compatible Hadoop and Spark workloads; the Cloud Storage connector separates durable object storage from cluster lifetime. **Dataflow/Beam** processes streams with explicit windowing and delivery semantics.
- For **Bigtable multi-cluster routing**, evaluate failover behavior and consistency requirements. For **Spanner**, monitor utilization and latency before reducing capacity; client session and connection reuse also affect performance.
Structured logs, routing and retention
- Write **single-line structured JSON** to stdout or stderr for managed container log collection. Include severity, request metadata, service identity and trace correlation; avoid secrets and high-cardinality sensitive fields.
- On VMs, configure the **Ops Agent** for application files and guest metrics such as memory. Platform metrics alone do not reveal every process or application behavior.
- Query **Cloud Logging** across cluster, namespace, workload and container labels for centralized diagnosis. **kubectl logs --previous** retrieves the previous container's output after a restart.
- A **log sink** filters and routes new matching entries: Pub/Sub for streaming integration, BigQuery for analytics, Cloud Storage for archival, or a log bucket for searchable retention.
- Give the sink's **writer identity** destination access. For security copies, route to a restricted project without losing required local copies; log sinks do not automatically backfill old entries.
- Set **log-bucket retention** for searchable compliance history and storage retention controls for protected archives. Use audit events for administrative changes and event-driven remediation or cache invalidation.
Monitoring and actionable alerts
- **Cloud Monitoring** tracks metrics and alert conditions. **Log-based metrics** derive counts or distributions from matching logs; ingest supported Prometheus metrics for application-level monitoring.
- Choose a **threshold** for excessive or insufficient utilization and **metric absence** for missing expected telemetry. Process-health monitoring and external uptime checks answer different availability questions.
- **Uptime checks** test user-visible endpoint reachability. Load-balancer checks decide backend eligibility; passing a backend check does not prove the entire user journey works.
- Define an **SLI** such as successful-request ratio and an **SLO** target over a window. Alert on sustained user impact or error-budget burn; tune windows and notifications to avoid noisy paging.
- For an **error ratio**, align failed and total request counts over the same interval and population. Absolute error counts alone cannot express a percentage requirement.
- Forward cloud alerts to an existing operations platform when useful. Use **GKE cluster notifications** for supported upgrades and security events rather than polling dashboards manually.
Traces, profiles and troubleshooting
- **Cloud Trace** shows request latency and dependency spans. Instrument with **OpenTelemetry** and propagate trace context across service boundaries so a slow call remains connected to the original request.
- Configure **sampling** deliberately and preserve sampled context where supported. Adding attributes to a trace does not create spans or guarantee that a request will be recorded.
- **Cloud Profiler** attributes sampled CPU or memory cost to functions and call stacks. Flame graphs reveal expensive code paths; host utilization charts alone do not identify the responsible function.
- **Error Reporting** groups recognized application exceptions and stack traces. Emit supported structured errors or recognizable stack traces; a generic stderr line alone may not create an error group.
- For **CrashLoopBackOff**, inspect Pod events, termination reason and previous logs. Distinguish application startup failure, OOM termination, probe failures and image-pull errors before changing capacity or IAM.
- Correlate **logs, metrics and traces** by resource and request context. Use boot serial logs for VM startup failures, profiles for code hotspots, and traces for latency across services.