Skip to content

fix(api): synchronize Listen and Shutdown - #790

Open
alexciuca wants to merge 1 commit into
Shopify:mainfrom
alexciuca:fix/api-listen-shutdown-race
Open

alexciuca wants to merge 1 commit into
Shopify:mainfrom
alexciuca:fix/api-listen-shutdown-race

Conversation

@alexciuca

Copy link
Copy Markdown

Listen writes server.http from its goroutine while Shutdown reads it from main, so Ctrl-C during startup is a data race. If Shutdown runs first, it sees nil and returns, and Listen then serves forever.

server.http is now guarded by a mutex, and Shutdown sets a stopped flag so a Listen that hasn't started serving returns nil. The lock is released before http.Server.Shutdown, which can block for up to wait_timeout. If Shutdown lands between the unlock and ListenAndServe, net/http returns ErrServerClosed, which Listen maps to nil.

Behavior change: Shutdown is final. Listen after Shutdown returns nil instead of serving, matching http.Server, which can't be reused. Nothing in the repo restarts a server.

Testing

  • TestShutdownBeforeListen fails on main even without -race.
  • TestConcurrentListenAndShutdown fails on main under -race.
  • make test and golangci-lint run pass.

Relation to #668

#668 targets the same issue but conflicts with main and hasn't been reviewed. It also still races: server.shutdown is assigned after initOnce.Do returns, so the sync.Once doesn't order that write with the read in Shutdown.

Replaces #789. Fixes #667

@alexciuca
alexciuca force-pushed the fix/api-listen-shutdown-race branch from 8209086 to 1d0c474 Compare November 6, 2026 17:22
Listen and Shutdown both use server.http without a lock, so Ctrl-C
during startup is a data race. If Shutdown runs first it does nothing,
and Listen keeps serving forever.

Add a mutex around server.http and a stopped flag, so Listen won't
start serving once Shutdown has been called.

Fixes Shopify#667
@alexciuca
alexciuca force-pushed the fix/api-listen-shutdown-race branch from 1d0c474 to f6ffd61 Compare November 6, 2026 17:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

cmd/server: SIGINT during initialization can cause a data race in ApiServer

1 participant