GcpIntermediate

Building and Deploying Applications on Google App Engine

8 min read

TL;DR

Learn how to deploy and scale applications on Google App Engine. This guide covers standard and flexible environments, configuration options, and best practices for optimal performance.

Building and Deploying Applications on Google App Engine

Executive Summary

App Engine is Google Cloud's managed platform for web applications and APIs: you deploy code or a container, and Google runs it behind a load balancer with automatic scaling, version management, and traffic splitting built in. The one decision that shapes everything else is the environment. The standard environment runs your code in a sandbox on managed runtimes, starts in seconds, and can scale to zero, so idle services cost nothing. The flexible environment runs your application in a Docker container on Compute Engine VMs, starts in minutes, never scales to zero, and gives you full network access and custom runtimes. This guide covers both, the app.yaml configuration that controls them, deployment and traffic management, and the operational practices that keep an App Engine service healthy and affordable.

Why This Matters

Choosing the wrong environment is expensive to undo because the two environments differ in networking, scaling economics, and available services. A latency-sensitive API on the flexible environment pays for always-on instances it may not need; a workload that needs background processes, native binaries, or direct VPC access will fight the standard environment's sandbox indefinitely. App Engine also makes it easy to create versions and split traffic, which is a gift for safe releases and a hazard for cost, because forgotten versions with minimum instances keep billing. Understanding the model before the first deploy is what separates a cheap, boring PaaS from a surprising invoice.

Core Concepts

Standard Environment: Managed Runtimes, Scale to Zero

In the standard environment you deploy code in a supported language runtime. Instances start quickly, and with automatic scaling the service can scale down to zero instances when idle. The constraints are the price of that convenience: no SSH access, restricted filesystem behaviour, request deadlines, and access to other Google services through App Engine's interfaces rather than arbitrary networking.

# main.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello from App Engine!'

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080, debug=True)

# app.yaml
runtime: python39
instance_class: F1

automatic_scaling:
  target_cpu_utilization: 0.65
  min_instances: 1
  max_instances: 10

handlers:
- url: /.*
  script: auto

Serve static content through handlers rather than your application code; App Engine serves those files from its own infrastructure, which is faster and does not consume instance hours:

# app.yaml
handlers:
- url: /static
  static_dir: static
  http_headers:
    Cache-Control: public, max-age=3600

- url: /.*
  script: auto

Flexible Environment: Containers on Managed VMs

The flexible environment takes a Dockerfile (or a runtime builder for supported languages) and runs it on Compute Engine instances that Google manages for you. You gain custom runtimes, SSH access for debugging, and full network access including VPC connectivity. You lose scale-to-zero: at least one instance runs at all times, and instance startup is measured in minutes, which changes both the cost profile and the scaling behaviour under spiky load.

# app.yaml
runtime: custom
env: flex

manual_scaling:
  instances: 2

resources:
  cpu: 1
  memory_gb: 2
  disk_size_gb: 10

env_variables:
  ENV: 'production'

FROM python:3.9-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
CMD gunicorn -b :$PORT main:app

Note the contract in the Dockerfile: the application must listen on the port given by the PORT environment variable. Almost every "deployed but 502" problem in the flexible environment is a violation of that contract or a failed health check.

Scaling Modes

App Engine offers three scaling modes, and app.yaml chooses among them. Automatic scaling adds and removes instances based on CPU, throughput, and concurrency targets; it is the default choice for web workloads. Basic scaling starts instances on demand and stops them after an idle timeout, suiting low-traffic and task-style workloads in the standard environment. Manual scaling fixes the instance count, which is appropriate for the flexible environment and for workloads whose load you understand better than an autoscaler does.

# Automatic scaling
automatic_scaling:
  target_cpu_utilization: 0.65
  target_throughput_utilization: 0.6
  min_instances: 1
  max_instances: 10
  max_concurrent_requests: 50

# Basic scaling
basic_scaling:
  max_instances: 5
  idle_timeout: 10m

# Manual scaling
manual_scaling:
  instances: 3

Setting min_instances above zero in the standard environment removes cold starts for the first requests and simultaneously removes the free idle state; set it deliberately, per service, and revisit it.

Versions and Traffic Splitting

Every deploy creates a version. Versions let you test a release on a small share of traffic, roll back by moving traffic rather than redeploying, and run A/B comparisons:

# Deploy application
gcloud app deploy app.yaml

# Deploy specific version
gcloud app deploy app.yaml --version=v1

# Deploy with traffic splitting
gcloud app deploy app.yaml --version=v2 --no-promote

# List versions
gcloud app versions list

# Split traffic
gcloud app services set-traffic default \
  --splits=v1=0.5,v2=0.5

# Migrate traffic
gcloud app services set-traffic default \
  --splits=v2=1 \
  --migrate

Deploy new versions with --no-promote, verify them on their version-specific URL, then migrate traffic. Delete old versions you no longer need; versions with allocated minimum instances are a recurring cost, not a free archive.

Configuration, Secrets, and Services Around the App

Environment variables live in app.yaml, which makes them configuration, not secrets storage. Anything sensitive in that file is committed to source control by design. Keep real secrets in Secret Manager and load them at startup, or inject them through your deployment pipeline:

env_variables:
  DATABASE_URL: 'postgresql://user:pass@host:5432/db'
  API_KEY: '${SECRET_KEY}'
  CACHE_TTL: '3600'

For data, the standard companions are Cloud SQL for relational data, Firestore (the successor to Datastore) for document data, Cloud Storage for files, and Cloud Tasks or Pub/Sub for asynchronous work that should not block a request. Caching belongs in Memorystore rather than in instance memory, because instances are replaceable:

# Using Memcache
from google.appengine.api import memcache

def get_data(key):
    data = memcache.get(key)
    if data is None:
        data = fetch_from_database(key)
        memcache.add(key, data, 3600)  # Cache for 1 hour
    return data

Security and Operations

Control who can deploy with IAM roles such as App Engine Deployer rather than broad project permissions, and use App Engine firewall rules to restrict source ranges for internal services. Custom domains and managed SSL certificates are configured at the platform level:

# Map custom domain
gcloud app domain-mappings create \
  --domain=www.example.com

# Create firewall rule
gcloud app firewall-rules create allow-internal \
  --action allow \
  --source-range 10.0.0.0/8 \
  --description "Allow internal traffic"

Operationally, watch instance count, request latency, error rate, and memory and CPU utilisation in Cloud Monitoring, and read logs with gcloud app logs tail or Cloud Logging queries filtered on the gae_app resource. Configure health checks explicitly in the flexible environment so unhealthy instances are replaced rather than left serving errors.

Decision Framework

SituationRecommendation
Standard web app or API in a supported language, spiky trafficStandard environment with automatic scaling
Idle or low-traffic service where cost matters mostStandard environment, minimum instances set to zero
Custom runtime, native dependencies, or background processesFlexible environment
Workload needs direct VPC access to internal resourcesFlexible environment, or standard with a Serverless VPC Access connector
Long-running work beyond request limitsMove it to Cloud Tasks, Cloud Run, or Compute Engine; do not stretch App Engine requests
New project with no App Engine legacyEvaluate Cloud Run first; choose App Engine when its versioning and services model fits better

Implementation Checklist

  • [ ] Environment (standard or flexible) chosen against networking, runtime, and scale-to-zero requirements
  • [ ] app.yaml sets explicit scaling bounds and instance class; minimum instances are justified
  • [ ] Static files are served via handlers or a CDN, not application instances
  • [ ] Secrets are in Secret Manager, not in app.yaml
  • [ ] New versions are deployed with --no-promote and verified before traffic migrates
  • [ ] Old versions are deleted; none hold idle minimum instances unnoticed
  • [ ] Health checks are configured and the application listens on PORT in the flexible environment
  • [ ] Alerts exist for error rate, latency, and instance count
  • Trade-offs

    The standard environment's sandbox is the price of its speed and scale-to-zero economics: runtime versions age, some libraries that need native or filesystem access will not work, and request deadlines shape your architecture whether you like it or not. The flexible environment removes most constraints but behaves like the VMs it is: slower to start, always at least partly on, and billed accordingly. Both environments tie you to Google's deployment and configuration model; porting away means rebuilding the deployment layer even when the application code itself is portable.

    When Not to Use

  • Long-running or background compute: batch jobs, video processing, and anything measured in hours belongs on Cloud Run jobs, Compute Engine, or GKE, not behind App Engine request handling.
  • WebSockets-heavy or stateful session designs: App Engine's model favours stateless request-response services; stateful real-time workloads are better served by Cloud Run or GKE with explicit session handling.
  • Fine-grained infrastructure control: if you need custom machine types, GPUs, or kernel-level tuning, you are describing Compute Engine or GKE, not a PaaS.
  • Conclusion

    App Engine remains a productive way to run web services when its model matches your workload: standard environment for fast, scale-to-zero services in supported runtimes, flexible for containers that need network freedom. The failures are predictable: wrong environment, secrets in app.yaml, and forgotten versions quietly billing. Decide those three things consciously and the platform mostly disappears, which is the point of a PaaS.

    Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.