Skip to content

Reduce DB round-trips, stream CSV parsing, and harden shutdown/error handling - #10

Merged
markmnl merged 2 commits into
mainfrom
review/perf-and-reliability
Nov 25, 2026
Merged

markmnl merged 2 commits into
mainfrom
review/perf-and-reliability

Conversation

@markmnl

@markmnl markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Summary

High-impact performance, reliability, and maintainability improvements from a Go code review:

Performance

  • Single-query GET /fmsgid/:address (src/sql.go, src/fmsgid.go): Combine the address lookup and quota-pool actuals aggregate into one CROSS JOIN LATERAL query via pool.QueryRow, cutting DB round-trips in half on the hottest read path.
  • Single row lock & skip no-op updates in registerAddress (src/sql.go, src/fmsgid.go): Merge the duplicate SELECT ... FOR UPDATE queries (quota_pool and accepting_new) into sqlSelectAddressStateForUpdate, and skip the UPDATE when neither requested column changes.
  • Avoid rewriting already-disabled rows during CSV sync (src/sql.go): Add and accepting_new predicate to sqlDisableAbsentAddresses.
  • Stream CSV parsing (src/csv.go): Use csv.Reader.Read() with ReuseRecord = true instead of ReadAll(), and resolve header column indices once instead of per-row map lookups and closure allocations.

Reliability & Correctness

  • Handle nullable display_name (src/sql.go): coalesce(a.display_name, '') prevents HTTP 500 scan failures when address.display_name is NULL.
  • Fix CSV watcher shutdown race & timer leak (src/csv.go): Drive debouncing from a time.Timer channel inside the watcher select loop instead of time.AfterFunc + mutex, preventing sync callbacks from firing after ctx cancellation / pool.Close(). Also check br.Close() error in syncCSV.
  • Server timeouts & graceful shutdown (src/fmsgid.go): Replace r.Run() with an explicit http.Server (ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout), trap SIGINT/SIGTERM via signal.NotifyContext, and drain HTTP requests + the CSV watcher before closing the DB pool. Switch c.BindJSON to c.ShouldBindJSON to avoid double-aborting on 400.

Testing

  • Added unit tests in src/fmsgid_test.go.
  • Verified with go vet ./... and go test -race -count=1 ./... in src/.

@markmnl markmnl left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No blocking issues. This one is good to merge as it stands; the four inline notes are optional.

What I ran

  • go vet and go test -race pass. I also ran the DB-backed tests against a throwaway PostgreSQL 17 with FMSGID_TEST_DATABASE_URL set: 25 pass, none skipped.
  • EXPLAIN ANALYZE of the new single-query address detail against the old second query, on 20k addresses and 640k address_tx rows. Same plan, same timings (table inline on sql.go).
  • The fmsg-docker integration suite with this branch together with fmsg-webapi #71 and fmsg-cli #20 (fmsgd on main): 16/16 pass.

What I checked by reading

  • registerAddress: the merged FOR UPDATE keeps the lock order (FOR SHARE on the pool owner, then the address row) and the claim / reinstated results. The only behaviour change is skipping an UPDATE that would write the values already there.
  • CSV watcher: the debounce now fires inside the select loop, so a sync can't start after the context is cancelled, and main waits for the watcher before the pool closes.
  • ShouldBindJSON: same 400, without gin writing the status twice.

One gap outside the diff
The workflow doesn't set FMSGID_TEST_DATABASE_URL, so every DB-backed test skips in CI. Nearly everything of substance in this PR is SQL, and the green check didn't execute any of it. A postgres service in the workflow, as fmsg-webapi's has, would close that.

🤖 Review by Claude Code

Comment thread src/fmsgid.go
wg.Wait()
log.Fatalf("ERROR: Running HTTP server: %s", err)
}
case <-ctx.Done():

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: call stop() as the first thing in this branch. signal.NotifyContext keeps swallowing SIGINT/SIGTERM until stop() runs, and here that is only the deferred call, so a second Ctrl-C during the (up to 15s) drain does nothing. Calling stop() restores default signal handling so a second signal terminates immediately. fmsg-webapi's version of this block already does it.

Comment thread src/csv.go Outdated
if debounce == nil {
debounce = time.NewTimer(500 * time.Millisecond)
} else {
if !debounce.Stop() {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: go.mod says go 1.27, and since Go 1.23 Timer.Stop/Reset guarantee no stale value is left in (or later sent on) C. The drain is dead code; this whole else can be debounce.Reset(500 * time.Millisecond). Harmless as written.

Comment thread src/sql.go
const sqlSelectAddressDetail string = `select
a.address
, a.display_name
, coalesce(a.display_name, '')

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good fix, and it is reachable: POST /fmsgid and CSV sync always write a non-NULL display_name, but the column is nullable, so any row written to the table another way 500s on GET today. There's no test pinning it though. A DB-backed case in usage_test.go that inserts a row without display_name and asserts 200 with "displayName":"" would stop it regressing.

Comment thread src/sql.go
from
address a
left join address o on o.address_lower = a.quota_pool
cross join lateral (

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked this doesn't cost the index. On PostgreSQL 17 with 20k addresses and 640k address_tx rows (analyzed), the plan is the same shape as the old sqlActuals: the pool-member array(...) is still an InitPlan evaluated once, feeding a bitmap index scan on address_tx_addr_type_ts.

lookup old (2nd query only) new (whole query)
address in no pool, 30 tx rows 0.38 ms 0.34 ms
member of a 40-address pool, 41k tx rows 9.0 ms 8.8 ms

So the saving is the round-trip, as the description says. One side effect worth having: limits and usage now come from one snapshot instead of two separate statements.

@markmnl

markmnl commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Addressed the inline review notes in b2f2e83:

  • Call stop() immediately upon receiving SIGINT/SIGTERM in main() so a second signal terminates immediately during drain.
  • Simplified debounce.Reset(500 * time.Millisecond) in src/csv.go (relying on Go 1.23+ timer semantics).
  • Added DB-backed TestAddressDetail_NullDisplayName in src/usage_test.go to pin coalesce(a.display_name, '').

@markmnl markmnl left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-checked at b2f2e83. All three notes are addressed and nothing new came up.

  • stop() is now the first statement of the shutdown branch.
  • The debounce is a plain Reset.
  • TestAddressDetail_NullDisplayName pins the coalesce.

CI still skips the DB-backed tests (no FMSGID_TEST_DATABASE_URL), so I ran the suite against a throwaway PostgreSQL 17: 26 pass, 0 skipped, including the new test. go vet and -race are clean, and the fmsg-docker suite passes 16/16 with this branch alongside the other three review/perf-and-reliability branches.

Good to merge from my side.

@markmnl
markmnl merged commit fc6ee65 into main Nov 25, 2026
1 check passed
@markmnl
markmnl deleted the review/perf-and-reliability branch November 25, 2026 13:24
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.

1 participant