Lesson 7 of 9 · 22m
Configuration, Secrets, and Observability in Vapor Services
Fail fast on missing configuration, keep secrets out of the repository, structure logs around request context, and expose health without leaking internals.
Production services rarely fail because a developer cannot read an environment variable. They fail because twelve variables exist, three are inconsistent, one default is dangerous, and nobody can tell whether the process is healthy or merely still listening.
Configuration should fail fast
struct AppConfig {
var databaseHost: String
var databasePassword: String
var publicBaseURL: URL
}
func loadConfig() throws -> AppConfig {
guard let host = Environment.get("DATABASE_HOST"),
let password = Environment.get("DATABASE_PASSWORD"),
let base = Environment.get("PUBLIC_BASE_URL").flatMap(URL.init(string:)) else {
fatalError("required configuration missing")
}
return AppConfig(databaseHost: host, databasePassword: password, publicBaseURL: base)
}Crash before accepting traffic if the service cannot operate correctly. A boot failure is visible; a silently wrong default is discovered by customers.
Secrets are not ordinary configuration
.env files are development conveniences. Production secrets belong in systemd credentials, Kubernetes or Docker secrets, a cloud secret manager, or your provisioning system. Treat anything printed in CI logs, tickets, screenshots, or git history as exposed and rotate it.
Logs are evidence
Attach request-scoped metadata once:
req.logger[metadataKey: "request_id"] = .string(requestID)
req.logger[metadataKey: "tenant_id"] = .string(user.tenantID.uuidString)
req.logger.info("project created", metadata: ["project_id": .string(projectID.uuidString)])Never log bearer tokens, passwords, cookies, authorization headers, or large user payloads. Log field names and lengths when shape matters.
Health checks answer different questions
api.get("health", "live") { _ in ["status": "live"] }
api.get("health", "ready") { req async throws in
// perform the driver's cheap database smoke query here
return ["status": "ready"]
}Liveness means the process can answer. Readiness means dependencies and initialization are sufficient for traffic. Keep responses small; do not dump dependency versions or host internals publicly.
Metrics and shutdown
Track latency, errors, request count, database pool pressure, queue depth, dependency latency, and memory. Label route templates rather than object IDs. During deploys, in-flight work should drain within a bounded time and background work should stop or hand off explicitly.
Field notes
- Production debug logging often leaks data and overwhelms storage.
- A secret printed once is compromised; rotate it.
- Health checks hitting every downstream service can cascade failures.
- If support cannot correlate a report to a request ID, logging is incomplete.
Was this lesson helpful?