Go Backend Advanced: A 7-Day Practice Path for Hand-Building Core Components

    Many Go developers write CRUD services for years but still struggle to improve their engineering and architecture skills. This article presents a practical 7-day practice route for building core backend components from scratch, with daily goals, runnable code, and acceptance criteria. It compares four routes—a lightweight Go web framework, an LRU-to-consistent-hashing cache path, a minimal ORM, and a minimal RPC framework—and explains how to choose one, avoid common mistakes, and build transferable design experience.

    Why CRUD Practice Rarely Builds Design Skills

    Many Go developers write business code for years and still follow the same routine: open the editor, define interfaces, connect to a database, and implement CRUD operations. Yet their engineering ability often improves very little. The issue is not that CRUD is useless. The issue is that business development usually involves using capabilities that someone else has already designed. Developers are often users of those capabilities rather than designers of them.

    A more effective exercise for improving architecture skills is to start from an empty directory and gradually build the core capabilities of a mature foundational component. This article does not promise that seven days will turn you into a senior engineer. The outcome depends on your Go foundation, how much time you can invest each day, how much code you write, and whether you complete the acceptance criteria. This method works best for developers who already have experience building APIs, are familiar with net/http, database/sql, and basic concurrency, and can turn ideas into runnable code.

    The goal here is not to memorize a roadmap. The goal is to provide an executable, verifiable, and reusable practice method: do one thing per day, make sure the code you write each day can run, and compare your implementation with the standard library or mature projects to identify gaps.


    How to Choose a 7-Day Practice Route: Start with a Table, Then Pick a Direction

    Different components train different skills. Before you start writing code, choose a route based on your target role, interests, and weaknesses. The table below compares four practical routes.

    Route Main Gains Difficulty Prerequisites Daily Acceptance
    Hand-write a lightweight Go Web framework Learn routing, middleware, request context, templates, and recovery Medium net/http, map, interfaces, defer The service can start, 404 and 405 work correctly, and middleware order can be verified
    Build a cache route from LRU to consistent hashing Learn cache eviction, concurrency safety, hash rings, and fallback strategies Medium list, map, sync.Mutex, HTTP interfaces LRU can read and write, hash nodes can be added or removed and located, and cache breakdown has protection
    Implement a minimal ORM Learn reflection, struct mapping, parameterized SQL, and transactions Higher database/sql, reflection, struct tags Insert, Find, Update, and rollback tests can be completed
    Implement a minimal RPC framework Learn network encoding, asynchronous calls, service registration, and timeout governance Higher net, reflect, context, goroutines Calls can be made, timeouts can be triggered, and service registration works

    Recommendations:

    1. If you are a web backend engineer, choose the web framework route first. It forms a complete loop most easily and makes it easier to bring routing, middleware, and error handling into the same mental model.
    2. If you are interested in high concurrency, caching, and distributed fundamentals, choose the distributed cache route. It connects data structures, concurrency, consistent hashing, and failure protection.
    3. If you frequently work with database tables, choose the ORM route. It helps you move from “knowing how to write SQL” to “understanding how SQL is packaged behind objects.”
    4. If you want to work on microservices or distributed systems, choose the RPC route. It connects network communication, service registration, timeout control, and call governance.

    How to Build a Lightweight Go Web Framework from Scratch

    Route one is a good first Go advanced practice route. The goal is not to reproduce every mainstream framework. The goal is to use about five hundred lines of core code to understand the minimum capabilities a web framework must have.

    Day 1: Understand http.Handler and Build a Minimal Runnable Version

    The core interface in Go’s standard library net/http is http.Handler. It has only one method:

    1. type Handler interface {
    2. ServeHTTP(http.ResponseWriter, *http.Request)
    3. }

    Your framework needs to implement this interface so that it can be mounted directly into http.ListenAndServe.

    Use Go 1.20 or later, and initialize the module:

    1. go version
    2. go mod init example.com/miniweb

    The goal for Day 1 is to start the service and handle requests. A minimal example can be:

    1. package main
    2. import (
    3. "fmt"
    4. "net/http"
    5. )
    6. type Engine struct{}
    7. func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    8. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    9. fmt.Fprintf(w, "method=%s path=%s\n", req.Method, req.URL.Path)
    10. }
    11. func main() {
    12. engine := &Engine{}
    13. http.ListenAndServe(":9999", engine)
    14. }

    The acceptance criterion for Day 1 is not “it looks like it runs.” The criterion is that it handles basic boundaries correctly:

    1. Return 404 when the path does not exist.
    2. Return 405 when the path exists but the method does not match.
    3. Request logs output the method, path, and status code.
    4. Responses can be verified with curl.

    For example:

    1. curl -i http://localhost:9999/
    2. curl -i -X POST http://localhost:9999/

    The core question to understand on this day is this: a framework does not exist out of nowhere. It must implement standard library interfaces, and it must handle common logic before request dispatch on behalf of the business layer.

    Day 2: Design Context to Make Business Code Cleaner

    If you only pass ResponseWriter and *Request to business functions, handling JSON, path parameters, query parameters, and response status codes becomes verbose. This is why you need a Context.

    At minimum, Context should encapsulate these capabilities:

    1. type Context struct {
    2. Writer http.ResponseWriter
    3. Request *http.Request
    4. }
    5. func (c *Context) JSON(code int, obj any) {
    6. c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
    7. c.Writer.WriteHeader(code)
    8. // Use json.NewEncoder to encode obj
    9. }
    10. func (c *Context) Param(name string) string {
    11. // Read the parameter from the route match result
    12. }
    13. func (c *Context) PostForm(name string) string {
    14. return c.Request.PostFormValue(name)
    15. }

    Day 2 acceptance criteria:

    1. It can return JSON.
    2. It can return strings.
    3. It can read query parameters.
    4. It can read path parameters.

    Day 3: Implement Routing with a Prefix Tree

    Do not start routing with a pile of if else statements. Instead, use a prefix tree and organize nodes by path segments.

    Core goals:

    1. Support static routes.
    2. Support :name wildcards.
    3. Support *filepath fallback matching.
    4. Distinguish HTTP methods.
    5. Return 404 when no route matches.
    6. Return 405 when the path exists but the method does not match.

    For example:

    1. GET /users
    2. POST /users
    3. GET /users/:id
    4. GET /static/*filepath

    Day 3 acceptance criteria:

    1. /users can return a user list.
    2. /users/123 can read id=123.
    3. A nonexistent path returns 404.
    4. Sending POST to /users returns 405 if only GET is registered.

    Day 4: Implement Group Controls

    Groups solve two problems: route prefix reuse and middleware binding.

    Example:

    1. v1 := r.Group("/v1")
    2. v1.GET("/users", handler)
    3. v1.POST("/users", handler)

    A group is essentially a way to pass the prefix and middleware chain further down. Large projects usually have groups such as /api/v1, /admin, and /public.

    Day 4 acceptance criteria:

    1. /v1/users can be accessed normally.
    2. Nested groups such as /api/v1 can be accessed normally.
    3. Middleware attached to a group only affects that group.

    Day 5: Implement the Middleware Chain

    The common middleware pattern is:

    1. type HandlerFunc func(*Context)
    2. type Middleware func(HandlerFunc) HandlerFunc

    The execution order can be designed as follows:

    1. Request enters
    2. -> Middleware A before logic
    3. -> Middleware B before logic
    4. -> Business handler
    5. -> Middleware B after logic
    6. -> Middleware A after logic

    Example of a logging middleware:

    1. func Logger() Middleware {
    2. return func(next HandlerFunc) HandlerFunc {
    3. return func(c *Context) {
    4. start := time.Now()
    5. c.Next()
    6. log.Printf("%s %s %d %v",
    7. c.Request.Method,
    8. c.Request.URL.Path,
    9. c.Writer.Status(),
    10. time.Since(start),
    11. )
    12. }
    13. }
    14. }

    On Day 5, you must verify middleware execution order. You can write three middlewares that print:

    1. before A
    2. before B
    3. handler
    4. after B
    5. after A

    If the order is wrong, your Next design has a problem.

    Day 6: Implement HTML Template Rendering

    Use the standard library html/template to load templates. The focus of this day is understanding:

    1. How template files are loaded.
    2. How template data is passed in.
    3. How static files are served.
    4. How to return an error page when a template is missing.

    Day 6 acceptance criteria:

    1. The /hello page can render a name.
    2. /static/style.css can serve static resources.
    3. A missing template does not crash the process.

    Day 7: Error Recovery and Request Boundary Handling

    A production-grade framework must be able to catch panics in the handling chain and prevent one request from taking down the whole service.

    Example:

    1. func Recovery() Middleware {
    2. return func(next HandlerFunc) HandlerFunc {
    3. return func(c *Context) {
    4. defer func() {
    5. if err := recover(); err != nil {
    6. log.Printf("panic: %v", err)
    7. c.JSON(500, map[string]string{
    8. "error": "internal server error",
    9. })
    10. }
    11. }()
    12. next(c)
    13. }
    14. }
    15. }

    Day 7 acceptance criteria:

    1. If a business handler panics intentionally, the service does not exit.
    2. The client receives a 500 error.
    3. The logs contain the panic stack.
    4. Subsequent requests can still be handled normally.

    How to Build a Cache Route from LRU to Consistent Hashing

    Route two trains data structures, concurrency control, and distributed fundamentals. The goal is not to build a production-grade cache. The goal is to connect the most important problems in caching.

    Day 1: Implement the LRU Eviction Strategy

    The key idea of LRU is “least recently used.” You can implement it with a doubly linked list plus a hash table:

    1. The hash table locates nodes quickly.
    2. The doubly linked list maintains access order.
    3. Get moves the node to the head.
    4. When Put reaches capacity, the tail node is removed.

    Day 1 acceptance criteria:

    1. When capacity is full, the least recently used element is evicted.
    2. The time complexity of Get and Put is close to O(1).
    3. Unit tests cover the eviction order.

    Day 2: Add Concurrency Protection to a Single-Machine Cache

    Add a lock around LRU:

    1. type Cache struct {
    2. mu sync.Mutex
    3. lru *LRU
    4. ttl map[string]time.Time
    5. }

    There are two problems to solve on Day 2:

    1. Concurrent reads and writes must not cause panics or data races.
    2. Once an item expires, it cannot be read, or it is returned as invalid.

    Day 2 acceptance criteria:

    1. go test -race shows no obvious races.
    2. Expired keys cannot be read after expiration.
    3. Concurrent reads and writes do not crash.

    Day 3: Expose the Cache as an HTTP Service

    A simple API design can be:

    1. GET /?key=hello
    2. POST /?key=hello&value=world
    3. DELETE /?key=hello

    Day 3 acceptance criteria:

    1. You can write to and read from the cache through HTTP.
    2. A miss can return 404 or nil.
    3. Basic logging and error handling are present.

    Day 4: Implement Consistent Hashing

    Consistent hashing solves the problem that adding or removing nodes causes large changes in cache mapping relationships.

    The core structure can be a hash ring:

    1. Hash nodes onto the ring.
    2. Hash keys onto the ring.
    3. From the key’s position, move clockwise to the first node.
    4. Introduce virtual nodes to reduce data skew.

    Day 4 acceptance criteria:

    1. After adding a node, only a small portion of keys are remapped.
    2. After deleting a node, only keys in the corresponding interval are remapped.
    3. Increasing the number of virtual nodes makes the distribution more even.

    Day 5: Implement Distributed Nodes and Routing

    Here, it is important to be precise. Distributed nodes do not mean that any node blindly fetches data from “unknown nodes.” Instead, the client or router selects the target node according to consistent hashing.

    Recommended flow:

    1. The client hashes the key with consistent hashing.
    2. The target node is found.
    3. The client sends a request to the target node.
    4. If the target node has a hit, it returns the data directly.
    5. If the target node misses, it falls back to storage.
    6. Depending on policy, the fallback result is written back to the target node or local cache.

    This can be represented as:

    1. Client requests key
    2. -> Consistent hashing selects target node
    3. -> Request sent to target node
    4. -> Target node hit: return data
    5. -> Target node miss: fall back to storage
    6. -> Fill cache according to policy

    Day 5 acceptance criteria:

    1. When nodes are added or removed, routing results match the hash ring’s expectations.
    2. When the target node misses, it can fall back to storage.
    3. The fill-back policy does not cause all nodes to fall back at the same time.
    4. Timeout control exists to prevent one node from dragging down the client.

    Day 6: Prevent Cache Breakdown

    When a hot key expires, a large number of requests may hit storage at the same time. You can use a singleflight-style approach to merge concurrent fallback requests.

    Production suggestions:

    1. Only one fallback request is allowed for the same key.
    2. Fallback requests must have timeouts.
    3. If fallback fails, return an error or a degraded value.
    4. Add rate limiting and circuit breaking if necessary.

    Day 6 acceptance criteria:

    1. Simulate 100 concurrent requests for the same missed key, and only one fallback request is produced.
    2. If fallback fails, requests do not wait forever.
    3. Logs show the number of merged hits.

    Day 7: Introduce Serialized Communication

    When nodes transfer data, you can use a more compact serialization format, such as binary encoding. The focus of this day is understanding:

    1. Why JSON is not always suitable for high-performance node communication.
    2. The protocol needs fields such as version number, key, value, and status code.
    3. Encoding and decoding errors must be detectable.

    Day 7 acceptance criteria:

    1. Nodes can encode requests and decode responses.
    2. Invalid data does not crash nodes.
    3. Basic performance comparison records are available.

    How to Implement a Minimal ORM Framework

    Route three is suitable for practicing reflection, metaprogramming, and SQL organization. The goal is not to write a complete ORM. The goal is to understand how objects map to tables and how SQL is generated by the framework.

    1. Understand database/sql First

    You need to understand:

    1. DB is a connection pool abstraction, not a single connection.
    2. Rows iterates over result sets.
    3. Parameterized queries must use placeholders whenever possible.
    4. Never concatenate user input directly into SQL.

    Minimal example:

    1. row := db.QueryRow("SELECT name FROM users WHERE id = ?", id)
    2. var name string
    3. err := row.Scan(&name)

    2. Use Structs and Struct Tags to Map Table Structures

    For example:

    1. type User struct {
    2. Id int64 `orm:"column(id);primary"`
    3. Name string `orm:"column(name)"`
    4. }

    Use reflection to read fields and tags, then generate the field list.

    3. Implement Insert and Find for Records

    First implement:

    1. db.Model(&User{}).Insert(&user)
    2. db.Model(&User{}).Where("id = ?", 1).Find(&users)

    Acceptance criteria:

    1. After insertion, a corresponding record exists in the database.
    2. Query results can be mapped back to struct fields.
    3. Parameterized SQL is used to avoid injection.

    4. Implement Chained Operations

    The key to a chained API is that each method returns itself so calls can be made continuously:

    1. db.Model(&User{}).
    2. Where("age > ?", 18).
    3. Update("status", 1)

    Acceptance criteria:

    1. Chained calls do not produce errors.
    2. The generated SQL matches expectations.
    3. Generated SQL can be logged for debugging.

    5. Implement Hooks

    You can design:

    1. type Hookable interface {
    2. BeforeInsert()
    3. AfterQuery()
    4. }

    Acceptance criteria:

    1. BeforeInsert is triggered before insertion.
    2. AfterQuery is triggered after querying.
    3. If a hook fails, the operation can roll back or stop.

    6. Transactions Must Have Acceptance Criteria

    Transactions are a difficult part of an ORM. You cannot only say “transactions are supported.” You must provide acceptance criteria:

    1. Rollback test: if the transaction returns an error in the middle, all prior writes must be undone.
    2. Isolation level explanation: at least state whether you use the database’s default isolation level or explicitly specify a level.
    3. Parameterized SQL: SQL inside transactions must also use placeholders.
    4. Connection pool configuration: set reasonable maximum connections, maximum idle connections, and connection lifetime.

    Example:

    1. tx, err := db.Begin()
    2. if err != nil {
    3. return err
    4. }
    5. _, err = tx.Exec("UPDATE accounts SET balance = balance - ? WHERE id = ?", 10, 1)
    6. if err != nil {
    7. tx.Rollback()
    8. return err
    9. }
    10. _, err = tx.Exec("UPDATE accounts SET balance = balance + ? WHERE id = ?", 10, 2)
    11. if err != nil {
    12. tx.Rollback()
    13. return err
    14. }
    15. return tx.Commit()

    Acceptance criteria:

    1. If the second SQL fails, the first SQL does not take effect.
    2. Unit tests simulate failure and rollback.
    3. Logs can record transaction start, commit, or rollback.

    7. Be Careful with Database Migrations

    Migration support is a bonus, but you must warn about risks. Before migrating a production database, back it up first, provide a dry-run mode, and avoid automatically dropping columns or tables.

    Recommended rules:

    1. By default, do not drop columns.
    2. Dropping columns requires explicit confirmation.
    3. Print the SQL that will be executed before migration.
    4. Provide a dry-run mode that only outputs SQL without executing it.
    5. In production, back up first, then migrate.
    6. Migration scripts should be versioned so they can be rolled back.

    The final takeaway from Route Three is not that you know how to write a few SQL statements. The takeaway is that you understand how the framework hides SQL behind objects.


    How to Implement a Minimal RPC Framework

    Route four is suitable for practicing network programming, service governance, and asynchronous calls. The goal is to understand how remote calls can be wrapped in a form similar to local method calls.

    Day 1: Run a Blocking Server and Client

    Start with the simplest version:

    1. The server listens on a TCP port.
    2. The client connects to the server.
    3. The request message contains the service name, method name, and arguments.
    4. The server calls the local method and returns the result.

    Do not focus on performance on this day. The goal is only to get the link working.

    Day 2: Implement an Asynchronous Client

    Introduce a Call mechanism:

    1. When the client starts a call, it generates a unique request ID.
    2. A goroutine sends the request.
    3. A channel waits for the response.
    4. The result is matched according to the request ID.

    Day 2 acceptance criteria:

    1. Multiple concurrent requests do not mix data.
    2. If a call fails, an error is returned.
    3. One stuck request does not block other requests.

    Day 3: Implement Service Registration

    Use reflection to map service methods to RPC requests:

    1. type Service struct {
    2. Name string
    3. Methods map[string]*Method
    4. }

    The key to service registration is validation:

    1. Whether method arguments can be serialized.
    2. Whether the number of return values matches expectations.
    3. Whether method names conflict.

    Day 4: Add Timeout Handling

    Use context to control call timeouts:

    1. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    2. defer cancel()

    Day 4 acceptance criteria:

    1. If the server responds slowly, the client can return an error after timeout.
    2. Timeouts do not cause goroutine leaks.
    3. Error messages can distinguish timeouts from unknown errors.

    Day 5: Support the HTTP Protocol

    Make the framework capable of running over plain TCP while also supporting HTTP. This makes debugging easier and helps integrate with gateways or monitoring systems.

    Day 6: Implement Simple Load Balancing

    Introduce strategies on the client side:

    1. Randomly select a node.
    2. Select nodes in round-robin order.
    3. Select nodes by consistent hashing.

    Acceptance criteria:

    1. Requests are distributed across multiple nodes.
    2. If a node fails, requests do not get stuck forever.
    3. There is node health checking or failure removal.

    Day 7: Implement Service Discovery

    Service discovery allows callers to dynamically obtain a list of service instances. A minimal version can be:

    1. Services register their address when they start.
    2. Clients pull instances by service name.
    3. The instance list is refreshed periodically.
    4. Unavailable instances are removed from the list.

    The final goal of Route Four is to understand how an RPC framework combines networking, reflection, asynchronous calls, timeouts, and governance.


    Extension Direction: WebAssembly as an Optional Read

    If you are already familiar with Go server-side development, you can treat WebAssembly as a supplementary direction. It is useful for understanding how Go can be compiled to run in browser or WASM runtime environments.

    Applicable scenarios:

    1. Writing frontend computation logic in Go.
    2. Reusing pure computation modules across platforms.
    3. Learning the boundaries of Go across different runtime forms.

    Minimal command:

    1. GOOS=js GOARCH=wasm go build -o main.wasm main.go

    You also need wasm_exec.js from the Go distribution. On the first day, you can start with three small experiments:

    1. Print Hello.
    2. Register functions with JavaScript.
    3. Manipulate the page DOM.

    If time is limited, this direction can be treated as a note. It does not need to occupy the main time of the 7-day route.


    How to Choose a Go Practice Project

    If you are not sure which route to start with, use this simple guide:

    1. If you want to improve web API design skills: choose the web framework.
    2. If you want to improve caching and concurrency skills: choose distributed caching.
    3. If you want to improve database encapsulation skills: choose ORM.
    4. If you want to improve distributed communication skills: choose RPC.
    5. If you have very little time: choose the web framework or cache, because they have higher completion rates.
    6. If your foundation is weak: first strengthen net/http, map, list, locks, and context.

    Do not start all four routes at the same time. Build one component at a time, and summarize after finishing it.


    Common Mistakes in the 7-Day Route

    Many practice attempts fail not because the route is difficult, but because the method is wrong. Common problems include:

    1. Writing too many abstractions on Day 1, resulting in no runnable version.
    2. Writing only code without acceptance criteria, so you do not know whether you are done.
    3. Not writing tests, and only trying things manually in a main function.
    4. Running migration features directly against a production database without backups or dry-run mode.
    5. Cache fallback without timeouts, which can overwhelm storage when hot keys expire.
    6. RPC calls without context timeouts, leading to more and more goroutines.
    7. Only reading your own code without comparing it with standard library source code.
    8. Not recording design decisions, then forgetting why you wrote code that way a few days later.

    Daily Checklist

    At the end of each day, check the following:

    1. Does the code compile?
    2. Is there a minimal test?
    3. Does the program run?
    4. Have you completed the day’s acceptance criteria?
    5. Have you recorded design decisions?
    6. Have you written down one problem to solve tomorrow?
    7. Have you compared with the standard library or a mature project?

    A good practice repository can be organized like this:

    1. mini-go-practice/
    2. day01-web-handler/
    3. day02-web-context/
    4. day03-web-router/
    5. day04-cache-lru/
    6. day05-cache-concurrent/
    7. day06-orm-mapper/
    8. day07-rpc-call/
    9. docs/
    10. Makefile
    11. README.md

    Keep each day’s subdirectory independent so it is easy to review and compare later.


    Conclusion

    Improving Go engineering ability does not come from collecting more tutorials. It comes from building the core skeleton of a foundational component by hand. The value of the 7-day breakdown is not the time itself. The value is that it breaks complex systems into small steps that are understandable, verifiable, and reviewable.

    After you complete at least one route among routing, middleware, concurrent caching, consistent hashing, ORM transactions, and RPC calls, you will have a clearer understanding of why frameworks are designed the way they are. That design experience is also easier to transfer to other projects. Start today: choose only one route, finish the runnable version for Day 1, and then move on to Day 2.