Specify a service and its invariants
Specify a service and its invariants
A capstone starts with a contract, not a framework. We will build a small word-count service: POST /jobs receives an ID and text, computes the number of whitespace-separated words using strings.Fields, and returns a saved result. For the same ID and exact text, repeated requests return the same result; a different text with the same ID is a conflict. An invariant is a property that must remain true even when requests arrive concurrently. Limit IDs to 1–64 ASCII letters, digits, hyphens and underscores; limit text to 4096 bytes; cap stored records and concurrent processing. These are deliberate lab limits, not universal production defaults.
package main
import ( "fmt" "strings")
func count(text string) int { return len(strings.Fields(text)) }func main() { fmt.Println(count(" Go\tفارسی Go\n")) fmt.Println(count(" \n"))}The result is deterministic: the example counts three fields, not Unicode code points or linguistic words. An empty or whitespace-only text is valid and returns zero. This is a synchronous service: success means the store accepted a result, not that an asynchronous queue merely accepted work. The sample store later in the chapter is in memory; successful responses therefore do not promise survival after a restart. A production specification must choose a durable storage contract before promising durability.
Expected output:
30Turn invariants into testable cases
package main
import ( "fmt")
func decision(old, incoming string, exists bool) string { if !exists { return "create" } if old == incoming { return "reuse" } return "conflict"}func main() { fmt.Println(decision("", "Go", false)) fmt.Println(decision("Go", "Go", true)) fmt.Println(decision("Go", "Rust", true))}Use the same decision inside the store’s atomic operation; a separate existence check followed by an unprotected write is a race. Map create to HTTP 201, reuse to 200, and conflict to 409. Define measurable acceptance: at most one stored row per ID, identical replays return the original result, invalid input never reaches storage, and the active job count never exceeds the configured capacity. Add latency and availability targets only after defining the workload and measurement method.
Expected output:
createreuseconflictTry it locally
Implement validateID(s) using the stated ASCII allowlist. Check job_1, an empty ID, a slash, and a 65-byte ID. Do not silently normalize IDs.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Capstone engineering 01: Specify a service and its invariants
Check the lesson objective before moving on.
A request reuses an existing ID with different text. What should the service do?
What does a 201 response guarantee in this in-memory lab?