Patterns for Production Cloud Run Services
January 15, 20261 min read
cloudgcparchitecture
After deploying dozens of services to Cloud Run, here are the patterns that have served me well.
Container Optimization
Multi-stage builds
FROM python:3.12-slim as builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --user -r requirements.txt
FROM python:3.12-slim
COPY --from=builder /root/.local /root/.local
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
Cold start reduction
- Keep container images small (<500MB)
- Use minimum instances for critical paths
- Lazy load heavy dependencies
Structured Logging
Cloud Run logs work best with structured JSON:
import json
import logging
class JSONFormatter(logging.Formatter):
def format(self, record):
return json.dumps({
"severity": record.levelname,
"message": record.getMessage(),
"time": self.formatTime(record),
})
Health Checks
Always expose a health endpoint:
@app.get("/health")
async def health():
return {"status": "healthy"}
Secrets Management
Use Secret Manager, never environment variables for sensitive data:
from google.cloud import secretmanager
def get_secret(name: str) -> str:
client = secretmanager.SecretManagerServiceClient()
response = client.access_secret_version(name=name)
return response.payload.data.decode()