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:
- 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.
- 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.
- 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.”
- 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:
type Handler interface {ServeHTTP(http.ResponseWriter, *http.Request)}
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:
go versiongo mod init example.com/miniweb
The goal for Day 1 is to start the service and handle requests. A minimal example can be:
package mainimport ("fmt""net/http")type Engine struct{}func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {w.Header().Set("Content-Type", "text/plain; charset=utf-8")fmt.Fprintf(w, "method=%s path=%s\n", req.Method, req.URL.Path)}func main() {engine := &Engine{}http.ListenAndServe(":9999", engine)}
The acceptance criterion for Day 1 is not “it looks like it runs.” The criterion is that it handles basic boundaries correctly:
- Return 404 when the path does not exist.
- Return 405 when the path exists but the method does not match.
- Request logs output the method, path, and status code.
- Responses can be verified with
curl.
For example:
curl -i http://localhost:9999/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:
type Context struct {Writer http.ResponseWriterRequest *http.Request}func (c *Context) JSON(code int, obj any) {c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")c.Writer.WriteHeader(code)// Use json.NewEncoder to encode obj}func (c *Context) Param(name string) string {// Read the parameter from the route match result}func (c *Context) PostForm(name string) string {return c.Request.PostFormValue(name)}
Day 2 acceptance criteria:
- It can return JSON.
- It can return strings.
- It can read query parameters.
- 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:
- Support static routes.
- Support
:namewildcards. - Support
*filepathfallback matching. - Distinguish HTTP methods.
- Return 404 when no route matches.
- Return 405 when the path exists but the method does not match.
For example:
GET /usersPOST /usersGET /users/:idGET /static/*filepath
Day 3 acceptance criteria:
/userscan return a user list./users/123can readid=123.- A nonexistent path returns 404.
- Sending POST to
/usersreturns 405 if only GET is registered.
Day 4: Implement Group Controls
Groups solve two problems: route prefix reuse and middleware binding.
Example:
v1 := r.Group("/v1")v1.GET("/users", handler)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:
/v1/userscan be accessed normally.- Nested groups such as
/api/v1can be accessed normally. - Middleware attached to a group only affects that group.
Day 5: Implement the Middleware Chain
The common middleware pattern is:
type HandlerFunc func(*Context)type Middleware func(HandlerFunc) HandlerFunc
The execution order can be designed as follows:
Request enters-> Middleware A before logic-> Middleware B before logic-> Business handler-> Middleware B after logic-> Middleware A after logic
Example of a logging middleware:
func Logger() Middleware {return func(next HandlerFunc) HandlerFunc {return func(c *Context) {start := time.Now()c.Next()log.Printf("%s %s %d %v",c.Request.Method,c.Request.URL.Path,c.Writer.Status(),time.Since(start),)}}}
On Day 5, you must verify middleware execution order. You can write three middlewares that print:
before Abefore Bhandlerafter Bafter 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:
- How template files are loaded.
- How template data is passed in.
- How static files are served.
- How to return an error page when a template is missing.
Day 6 acceptance criteria:
- The
/hellopage can render a name. /static/style.csscan serve static resources.- 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:
func Recovery() Middleware {return func(next HandlerFunc) HandlerFunc {return func(c *Context) {defer func() {if err := recover(); err != nil {log.Printf("panic: %v", err)c.JSON(500, map[string]string{"error": "internal server error",})}}()next(c)}}}
Day 7 acceptance criteria:
- If a business handler panics intentionally, the service does not exit.
- The client receives a 500 error.
- The logs contain the panic stack.
- 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:
- The hash table locates nodes quickly.
- The doubly linked list maintains access order.
Getmoves the node to the head.- When
Putreaches capacity, the tail node is removed.
Day 1 acceptance criteria:
- When capacity is full, the least recently used element is evicted.
- The time complexity of
GetandPutis close to O(1). - Unit tests cover the eviction order.
Day 2: Add Concurrency Protection to a Single-Machine Cache
Add a lock around LRU:
type Cache struct {mu sync.Mutexlru *LRUttl map[string]time.Time}
There are two problems to solve on Day 2:
- Concurrent reads and writes must not cause panics or data races.
- Once an item expires, it cannot be read, or it is returned as invalid.
Day 2 acceptance criteria:
go test -raceshows no obvious races.- Expired keys cannot be read after expiration.
- Concurrent reads and writes do not crash.
Day 3: Expose the Cache as an HTTP Service
A simple API design can be:
GET /?key=helloPOST /?key=hello&value=worldDELETE /?key=hello
Day 3 acceptance criteria:
- You can write to and read from the cache through HTTP.
- A miss can return 404 or nil.
- 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:
- Hash nodes onto the ring.
- Hash keys onto the ring.
- From the key’s position, move clockwise to the first node.
- Introduce virtual nodes to reduce data skew.
Day 4 acceptance criteria:
- After adding a node, only a small portion of keys are remapped.
- After deleting a node, only keys in the corresponding interval are remapped.
- 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:
- The client hashes the key with consistent hashing.
- The target node is found.
- The client sends a request to the target node.
- If the target node has a hit, it returns the data directly.
- If the target node misses, it falls back to storage.
- Depending on policy, the fallback result is written back to the target node or local cache.
This can be represented as:
Client requests key-> Consistent hashing selects target node-> Request sent to target node-> Target node hit: return data-> Target node miss: fall back to storage-> Fill cache according to policy
Day 5 acceptance criteria:
- When nodes are added or removed, routing results match the hash ring’s expectations.
- When the target node misses, it can fall back to storage.
- The fill-back policy does not cause all nodes to fall back at the same time.
- 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:
- Only one fallback request is allowed for the same key.
- Fallback requests must have timeouts.
- If fallback fails, return an error or a degraded value.
- Add rate limiting and circuit breaking if necessary.
Day 6 acceptance criteria:
- Simulate 100 concurrent requests for the same missed key, and only one fallback request is produced.
- If fallback fails, requests do not wait forever.
- 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:
- Why JSON is not always suitable for high-performance node communication.
- The protocol needs fields such as version number, key, value, and status code.
- Encoding and decoding errors must be detectable.
Day 7 acceptance criteria:
- Nodes can encode requests and decode responses.
- Invalid data does not crash nodes.
- 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:
DBis a connection pool abstraction, not a single connection.Rowsiterates over result sets.- Parameterized queries must use placeholders whenever possible.
- Never concatenate user input directly into SQL.
Minimal example:
row := db.QueryRow("SELECT name FROM users WHERE id = ?", id)var name stringerr := row.Scan(&name)
2. Use Structs and Struct Tags to Map Table Structures
For example:
type User struct {Id int64 `orm:"column(id);primary"`Name string `orm:"column(name)"`}
Use reflection to read fields and tags, then generate the field list.
3. Implement Insert and Find for Records
First implement:
db.Model(&User{}).Insert(&user)db.Model(&User{}).Where("id = ?", 1).Find(&users)
Acceptance criteria:
- After insertion, a corresponding record exists in the database.
- Query results can be mapped back to struct fields.
- 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:
db.Model(&User{}).Where("age > ?", 18).Update("status", 1)
Acceptance criteria:
- Chained calls do not produce errors.
- The generated SQL matches expectations.
- Generated SQL can be logged for debugging.
5. Implement Hooks
You can design:
type Hookable interface {BeforeInsert()AfterQuery()}
Acceptance criteria:
BeforeInsertis triggered before insertion.AfterQueryis triggered after querying.- 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:
- Rollback test: if the transaction returns an error in the middle, all prior writes must be undone.
- Isolation level explanation: at least state whether you use the database’s default isolation level or explicitly specify a level.
- Parameterized SQL: SQL inside transactions must also use placeholders.
- Connection pool configuration: set reasonable maximum connections, maximum idle connections, and connection lifetime.
Example:
tx, err := db.Begin()if err != nil {return err}_, err = tx.Exec("UPDATE accounts SET balance = balance - ? WHERE id = ?", 10, 1)if err != nil {tx.Rollback()return err}_, err = tx.Exec("UPDATE accounts SET balance = balance + ? WHERE id = ?", 10, 2)if err != nil {tx.Rollback()return err}return tx.Commit()
Acceptance criteria:
- If the second SQL fails, the first SQL does not take effect.
- Unit tests simulate failure and rollback.
- 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:
- By default, do not drop columns.
- Dropping columns requires explicit confirmation.
- Print the SQL that will be executed before migration.
- Provide a dry-run mode that only outputs SQL without executing it.
- In production, back up first, then migrate.
- 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:
- The server listens on a TCP port.
- The client connects to the server.
- The request message contains the service name, method name, and arguments.
- 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:
- When the client starts a call, it generates a unique request ID.
- A goroutine sends the request.
- A channel waits for the response.
- The result is matched according to the request ID.
Day 2 acceptance criteria:
- Multiple concurrent requests do not mix data.
- If a call fails, an error is returned.
- One stuck request does not block other requests.
Day 3: Implement Service Registration
Use reflection to map service methods to RPC requests:
type Service struct {Name stringMethods map[string]*Method}
The key to service registration is validation:
- Whether method arguments can be serialized.
- Whether the number of return values matches expectations.
- Whether method names conflict.
Day 4: Add Timeout Handling
Use context to control call timeouts:
ctx, cancel := context.WithTimeout(context.Background(), time.Second)defer cancel()
Day 4 acceptance criteria:
- If the server responds slowly, the client can return an error after timeout.
- Timeouts do not cause goroutine leaks.
- 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:
- Randomly select a node.
- Select nodes in round-robin order.
- Select nodes by consistent hashing.
Acceptance criteria:
- Requests are distributed across multiple nodes.
- If a node fails, requests do not get stuck forever.
- 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:
- Services register their address when they start.
- Clients pull instances by service name.
- The instance list is refreshed periodically.
- 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:
- Writing frontend computation logic in Go.
- Reusing pure computation modules across platforms.
- Learning the boundaries of Go across different runtime forms.
Minimal command:
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:
- Print Hello.
- Register functions with JavaScript.
- 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:
- If you want to improve web API design skills: choose the web framework.
- If you want to improve caching and concurrency skills: choose distributed caching.
- If you want to improve database encapsulation skills: choose ORM.
- If you want to improve distributed communication skills: choose RPC.
- If you have very little time: choose the web framework or cache, because they have higher completion rates.
- If your foundation is weak: first strengthen
net/http,map,list, locks, andcontext.
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:
- Writing too many abstractions on Day 1, resulting in no runnable version.
- Writing only code without acceptance criteria, so you do not know whether you are done.
- Not writing tests, and only trying things manually in a
mainfunction. - Running migration features directly against a production database without backups or dry-run mode.
- Cache fallback without timeouts, which can overwhelm storage when hot keys expire.
- RPC calls without
contexttimeouts, leading to more and more goroutines. - Only reading your own code without comparing it with standard library source code.
- 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:
- Does the code compile?
- Is there a minimal test?
- Does the program run?
- Have you completed the day’s acceptance criteria?
- Have you recorded design decisions?
- Have you written down one problem to solve tomorrow?
- Have you compared with the standard library or a mature project?
A good practice repository can be organized like this:
mini-go-practice/day01-web-handler/day02-web-context/day03-web-router/day04-cache-lru/day05-cache-concurrent/day06-orm-mapper/day07-rpc-call/docs/MakefileREADME.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.
