Production HTTPS Compose stack
You build the production Compose stack that serves the API through Caddy over HTTPS and waits for a successful migration before startup.
Ticket
Build the production Compose deployment for the Go API. Caddy terminates HTTPS and proxies requests to the API, a one-shot service applies database migrations, and the API exposes separate liveness and readiness handlers.
The health package exports exactly the declarations the tests call:
import (
"context"
"net/http"
"time"
)
type Check func(ctx context.Context) error
func Healthz() http.Handler
func Readyz(timeout time.Duration, checks map[string]Check) http.HandlerThe order service needs a public HTTPS entry point, but traffic should not reach the API before its database schema is ready. The next exercise, "Nightly mysqldump and one restore test", uses this production stack to run and verify database backups.
Acceptance criteria
backend/Caddyfileuses{$API_DOMAIN}as its site address and proxies requests toapi:8080withreverse_proxy. Leave automatic HTTPS enabled: do not use anhttp://site address,auto_https off, ortls internal.backend/Caddyfileconfigures the reverse proxy's upstream health check withhealth_uri /readyz.backend/compose.prod.ymlpublishes ports80and443from the Caddy service, mounts./Caddyfileat/etc/caddy/Caddyfile, mounts the named volumecaddy_dataat/data, and makes Caddy depend on the API.backend/compose.prod.ymldoes not publish API, worker, MySQL, Redis, or Redpanda ports on all host interfaces. Any host port mappings for these services must bind to127.0.0.1.backend/compose.prod.ymldefines amigrateservice using an image whose name begins withmigrate/migrate. It runs as a one-shot job without restarting, mounts./db/migrations, and depends on MySQL withcondition: service_healthy. The API depends on the migration service withcondition: service_completed_successfully.- The migration command in
backend/compose.prod.ymlcontains-path, amysql://database URL, andup. - The API health check in
backend/compose.prod.ymluses the shell-freeCMDform and invokes the binary with its-healthcheckflag. backend/.env.examplecontainsAPI_DOMAIN=localhost.internal/health:Healthz()always returns HTTP200, sets aContent-Typebeginning withapplication/json, and returns JSON containing{"ok":true}.internal/health: when themysql,redis, andkafkachecks all succeed,Readyz()returns HTTP200, astatusfield of"ok", and"ok"for each dependency in thechecksobject.internal/health: when theredisandkafkachecks fail whilemysqlsucceeds,Readyz()returns HTTP503, astatusfield of"unavailable", and a sortedfailinglist containing["kafka","redis"]. The healthymysqlcheck must remain marked"ok".internal/health: readiness responses never include internal dependency error text. A failure containingdial tcp,10.0.3.7, orhunter2must not expose those strings in the response.internal/health: a dependency check that waits for its context to expire after a50 mstimeout is reported as unavailable. With the test's slowkafkacheck, the response is HTTP503,failingcontains["kafka"], and the handler completes in less than one second.internal/health: readiness checks execute concurrently. Three checks that each take150 msmust complete together in less than320 ms, with an HTTP200response when they succeed.internal/health:Healthz()does not invoke dependency checks. A call to/healthzleaves the check count at zero; a subsequent/readyzcall invokes the configured check exactly once.
Constraints
- Give each readiness check its own timeout context using the timeout supplied to
Readyz(). - Run readiness checks concurrently. The three-check timing case must complete in less than
320 ms. - A check that respects its context must be bounded by its timeout. The supplied
50 mstimeout case must return within one second. - Any host port mappings for services other than Caddy must bind to
127.0.0.1. - Do not modify the provided tests.
Design direction
Keep dependency checks and HTTP response construction in backend/internal/health/health.go. Use Check as the common function type so the handler does not need to know whether a check uses MySQL, Redis, or Kafka. Keep dependency client construction in backend/cmd/api/health.go. Add the -healthcheck execution mode in backend/cmd/api/healthcheck.go.
Register /healthz with health.Healthz() and /readyz with health.Readyz(2*time.Second, checks). Replace the old inline health route with a call to registerHealth(router). Configure checks only for dependencies whose corresponding environment variables are present. Use the context-aware ping methods of database/sql, go-redis, and franz-go.
Keep liveness independent of dependencies. A process can be alive while MySQL is unavailable. Caddy should use readiness so it can avoid sending traffic to an API whose dependencies are unavailable.
Use the migration service as a startup gate. It should wait for healthy MySQL, mount the existing migration files read-only, and exit after applying migrations. The API and worker should both wait for healthy infrastructure and successful migration completion. This separates container health from application schema readiness.
Keep Caddy as the public reverse proxy. Its named volumes should preserve certificate data and configuration across restarts. The API's health check must invoke its binary directly because the distroless image has no shell. Any layout that meets the contract passes.
How to check your work
Run the Go tests first, then run the production stack check from the same directory:
cd backend
make test W=7B3
./scripts/check-w7-b3.shThe helper starts the production Compose stack using .env.example and checks service health, HTTPS endpoints, the HTTP-to-HTTPS redirect, and migration completion. It uses curl -k for the local certificate. Confirm that https://localhost/healthz returns HTTP 200 and https://localhost/readyz reports readiness.
When a test fails, read the first failing assertion. It identifies the file or response field that does not match the contract.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
- Health handlers return the expected status codes and JSON.
- Readiness checks run concurrently with independent timeouts.
- Failed dependencies are identified without exposing error text.
- Caddy proxies HTTPS traffic and checks
/readyz. - Migrations complete before the API starts.
- The production stack check passes.
Commands
cd backend && make test W=7B3cd backend && ./scripts/check-w7-b3.shTests
TestW7B3_CaddyfileProxiesTheConfiguredDomainToTheApiinbackend/internal/deploy/w7b3_test.goTestW7B3_CaddyHealthChecksTheApiThroughReadyzinbackend/internal/deploy/w7b3_test.goTestW7B3_CaddyServiceExposesWebPortsAndPersistsCertificatesinbackend/internal/deploy/w7b3_test.goTestW7B3_OnlyCaddyIsPublishedToTheInternetinbackend/internal/deploy/w7b3_test.goTestW7B3_MigrationsRunAsAOneShotMigrateServiceBeforeTheApiinbackend/internal/deploy/w7b3_test.goTestW7B3_MigrateDatabaseUrlComesFromTheEnvFileinbackend/internal/deploy/w7b3_test.goTestW7B3_ApiHasAHealthcheckThatNeedsNoShellinbackend/internal/deploy/w7b3_test.goTestW7B3_EnvExampleDefaultsToALocalDomaininbackend/internal/deploy/w7b3_test.goTestW7B3_HealthzIsAlwaysOkAndJSONinbackend/internal/health/health_test.goTestW7B3_ReadyzIsOkWhenEveryDependencyIsHealthyinbackend/internal/health/health_test.goTestW7B3_ReadyzReturns503NamingEveryFailingDependencyinbackend/internal/health/health_test.goTestW7B3_ReadyzNeverLeaksErrorTextinbackend/internal/health/health_test.goTestW7B3_ReadyzFailsASlowDependencyAfterTheTimeoutinbackend/internal/health/health_test.goTestW7B3_ReadyzRunsChecksConcurrentlyinbackend/internal/health/health_test.goTestW7B3_HealthzNeverCallsDependencyChecksinbackend/internal/health/health_test.go