CodeGym /행동 /Go SELF /context rules: do not store business data

context rules: do not store business data

Go SELF
레벨 70, 레슨 1
사용 가능

1. Why rules around context are needed

When you first see context.Context, it feels like something along the lines of “a little packet we carry everywhere because that is how it is done”. And there is some truth in that: in Go, many things are “done that way” because people have already learned the hard way. Context is exactly such a story: using it incorrectly rarely breaks the program right away, but it very effectively breaks it later, under load, and at the worst possible moment (that is, always).

The right mental model is this: context is a companion document bundle for one operation. That bundle contains information about the operation’s lifetime (timeouts/deadlines), cancellation support, and a bit of metadata. But it is not “a backpack where we throw everything we do not want to pass as parameters”.

If you mix up these roles, you get code that works in a demo, but suddenly “gets stuck” in production, loses cancellation, picks up somebody else’s timeouts, and generally lives like a cat: on its own.

2. Rule #1: do not store business data in context

Beginners trip over this rule most often, because it hits a very human desire: “oh, I need to pass one more parameter… let’s just shove it into context so I do not have to change the signatures”. In programming, that is called “quickly, for five minutes”; in support, it is called “so why did everything break after three months”.

What business data means in this context

Business data is everything related to your application’s domain: userID, taskID, user role, task filter parameters, selected project, task content, access rules, tariff configuration, and so on. This is data without which the meaning of the operation changes, not just its “formatting”.

Operation metadata is what helps you perform or trace the operation, but does not change its business meaning. Example: request_id for logs, a deadline, a “who initiated the cancellation” flag.

To make it easier to distinguish them, keep this table in mind:

Question If the answer is “yes” — this is business data If the answer is “no” — it may be metadata
Will the result of the operation change if the value is different? yes no
Is it part of the domain model (user, task, project)? yes no
Does it need to be explicit in the signature so the contract is clear? yes not always
Does it look like a “service label” for logs/tracing? no yes

Typical anti-pattern: “let’s pass userID through ctx”

Let us imagine our training project — a task manager (todo). We want to create a task. A bad idea looks like this: do not pass the user as a parameter, but “pull” it from the context.

package app

import "context"

func CreateTask(ctx context.Context, title string) error {
    userID := ctx.Value("user_id").(int) // panic if missing or wrong type
    _ = userID
    _ = title
    return nil
}

The problem here is not even that a string key is used (that is bad too), but that the function contract is hidden. From the signature it seems like: “create a task by title”, but in fact it is: “create a task for a user hidden somewhere”.

Then you call CreateTask(ctx, "buy milk"), and it crashes because you forgot to put user_id into the context. Or, more amusingly, it uses the wrong user because the context is not the right one. It is like signing documents with invisible ink: formally the signature is there, but finding it is a separate quest.

The normal way: make business data explicit parameters

The correct approach is to pass business values explicitly. Yes, the signatures get longer. But the code becomes clearer, and bugs become more visible.

package app

import "context"

func CreateTask(ctx context.Context, userID int, title string) error {
    _ = ctx      // context is about lifetime/cancellation
    _ = userID   // business data
    _ = title
    return nil
}

This is not “formality”. It is contract documentation at the compiler level: you cannot call the function without specifying the user.

If there are many parameters, we usually collect them in a request struct (this is very Go: “a small struct instead of ten arguments”):

package app

import "context"

type CreateTaskRequest struct {
    UserID int
    Title  string
}

func CreateTask(ctx context.Context, req CreateTaskRequest) error {
    _ = ctx
    _ = req
    return nil
}

Now your code is readable by a person, and they do not have to guess what is inside the context. They can see it in the types.

Why storing business data in context is dangerous

The problem is that, by meaning, context belongs to the operation, while business data belongs to the model. An operation can be reused, cancelled, forked into multiple goroutines, limited by a deadline — while business data must remain deterministic and explicit.

Another practical reason: context is easy to “reset” by mistake. It is enough for one layer to use context.Background() instead of the incoming ctx, and your “hidden parameters” disappear. Then someone in the code writes .Value(...).(int) — and hello, panic. That is why “hiding meaning” in context is like keeping apartment keys under the doormat: yes, convenient, until the wrong person finds them (or until you forget which doormat).

3. Rule #2: do not keep context inside a struct for a long time

At first glance, it seems logical: “I have a service/client/worker, let it store ctx inside so I do not have to pass it to every method”. But in Go this is considered bad practice precisely because it breaks the understanding of lifetime and makes the API muddy. Official guidance usually stresses that storing context in a struct mixes different lifetime scopes and makes it harder to set deadlines/cancellation for a specific call.

What bad design looks like

Here is an example of “how not to do it”:

package app

import "context"

type TaskServiceBad struct {
    ctx context.Context
}

func NewTaskServiceBad(ctx context.Context) *TaskServiceBad {
    return &TaskServiceBad{ctx: ctx}
}

func (s *TaskServiceBad) Create(title string) error {
    _ = s.ctx // one shared context for all calls
    _ = title
    return nil
}

From the outside, this looks convenient: no need to pass ctx every time. But now a number of uncomfortable questions arise (and this is not philosophy; these are real future bugs).

What does the ctx passed to NewTaskServiceBad belong to? Is it the service initialization context? Is it the context of “the whole program”? Is it the context of one HTTP request? What happens if the service lives for a year but the context was created for 2 seconds? Spoiler: the service turns into a pumpkin, and all methods immediately start returning context deadline exceeded because ctx has already finished.

In addition, such a service cannot be used correctly in scenarios where each call has its own deadline or cancellation. In a real system, “one shared ctx for everything” is almost never what you want.

Good design: ctx comes with every call

The normal Go approach is to make ctx the first argument of a method/function:

package app

import "context"

type TaskService struct{}

func NewTaskService() *TaskService {
    return &TaskService{}
}

func (s *TaskService) Create(ctx context.Context, title string) error {
    _ = ctx
    _ = title
    return nil
}

Now everything is transparent: lifetime is set at the “Create” operation level. Want a 200ms timeout — set it above and pass it down. Want to cancel — cancel it above. The service itself does not do “magic” and does not keep someone else’s lifetime in its pocket.

“But sometimes context in a struct is okay!” — when is it acceptable?

Yes, in the standard library you have seen context inside http.Request. That is done for backward compatibility reasons: the API existed before context, and support had to be added without breaking signatures.

The key point is that http.Request is an object that already represents one operation (one request). In other words, its lifetime is limited by the request lifetime. Therefore, storing ctx inside it is logical and does not turn into an “eternal context for all occasions”.

But in your code, Service, Repository, Client, and similar objects usually live longer than a single operation. So storing ctx there “for a long time” is almost always a mistake.

4. Passing ctx through layers in an application

Now we will assemble the familiar layered picture: an HTTP handler calls a service, and the service calls storage. Our goal is for the context to travel the same path, without being replaced by Background() and without trying to hide business data.

Let us imagine minimal interfaces in a todo application.

package app

import "context"

type TaskRepo interface {
    Create(ctx context.Context, userID int, title string) (int, error)
}

type TaskService struct {
    repo TaskRepo
}

func NewTaskService(repo TaskRepo) *TaskService {
    return &TaskService{repo: repo}
}

Notice: TaskService stores a dependency (the repository), but does not store context. This is “allowed storage”: dependencies live as long as the service. Context does not.

Now the service method:

package app

import "context"

func (s *TaskService) CreateTask(ctx context.Context, userID int, title string) (int, error) {
    if err := ctx.Err(); err != nil {
        return 0, err
    }
    return s.repo.Create(ctx, userID, title)
}

Here we do an early ctx.Err() check. It is not strictly required in every function, but it is a good guard clause: if we have already been cancelled, we do not start working.

The HTTP layer (very simplified, without full JSON decoding):

package httpapi

import (
    "net/http"
    "strconv"
)

func (h *Handler) createTask(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()

    userID, _ := strconv.Atoi(r.URL.Query().Get("user"))
    title := r.URL.Query().Get("title")

    _, _ = h.svc.CreateTask(ctx, userID, title)
    w.WriteHeader(http.StatusCreated)
}

The important idea here is: userID and title do not come from context. They are part of the request by meaning. We take the context from r.Context() and pass it along for cancellation/timeouts.

If later you want to set a timeout at the boundary, you will do it in the handler (or middleware), but still from r.Context(), not from Background().

5. Practical signals and acceptable data in context

How to tell that you are breaking the rules

In this section, I want to give you not “commandments on a stone tablet”, but human signs that you are moving toward pain. Usually the violations reveal themselves in the same way: “unexplained magic” starts appearing, along with strange dependencies between calls.

If you see code where a function accepts ctx, but inside it creates context.Background() “because it is easier”, that almost always means you just cut the cancellation/timeout wires, and the upper layer no longer controls the lower layer’s lifetime.

package storage

import "context"

func (r *Repo) Create(ctx context.Context, userID int, title string) error {
    _ = ctx
    ctx = context.Background() // bad: cancellation and deadline are lost
    _ = userID
    _ = title
    return nil
}

If you see a struct with a ctx context.Context field, and that struct lives a long time (service, client, repo), it almost always means: you will have a shared “eternal context” that either expires too early or gets cancelled by the wrong thing. This is exactly the situation usually described as “context in structs leads to confusion”.

And if you see .Value(...) used to retrieve business data, and it is not logging/tracing, then you are probably hiding the meaning of the operation in a place where nobody expects to find it.

What you can store in context

It is important not to draw the wrong conclusion: “so context cannot be used for data at all”. It can — but only for operation metadata. A classic example is request_id, which is needed to correlate logs from different layers for one request.

But even here we keep discipline: this data must not change the business result. It should help with diagnostics, tracing, logging, and sometimes authorization at the boundary (but not as a “secret parameter transport”).

Also remember that ctx.Value returns any, and any extraction requires care. That is why helper functions are usually used, so that “pulling values out” does not get spread across the entire codebase. (We will unpack this properly and in an adult way in the adjacent topic about WithValue.)

6. Typical mistakes

Mistake #1: “Let us temporarily put userID in context, we will refactor it later.”
That is almost never “temporary” and almost always “forever”, because once the code starts working, the motivation to refactor drops to the level of a battery in an old remote control. After some time, you discover that half the functions silently depend on a value being present in context, and any new entry point (CLI, test, another handler) starts failing or behaving strangely.

Mistake #2: “The service needs context anyway, let us put it in a struct field.”
The problem does not show up immediately: first everything is fine, then a second usage scenario appears for the service (different timeout, different cancellation), and you realize the service got “stuck” in one lifetime. This makes the API non-obvious and prevents you from setting deadlines for specific calls. That is exactly why storing context in a struct is considered a source of confusion.

Mistake #3: Replacing the incoming ctx with context.Background() “inside, just in case”.
In this way you break the “cancellation chain”: the upper layer can cancel the request, but the lower layer continues to work, consuming resources. Under load, this leads to a buildup of stuck operations and a very unpleasant “everything is slow, but there are no errors” effect.

Mistake #4: Mixing business data and metadata in context.
Even if you store request_id in context for logs, do not put “current task”, “user permissions”, or “filter parameters” there as well. That breaks contract transparency: from the signature, it is unclear what the result depends on. In the end, you lose the main advantage of Go code: readability through explicit types and parameters.

Mistake #5: Retrieving a value from context using .Value(...).(T) without checking.
In such code, the “missing value” error turns into a panic, and often not where you forgot to put the value, but deep in the stack. Even if it is only metadata, extraction must be safe (with a type check), otherwise you get a fragile system that crashes because of one wrong call.

1
과제
Go SELF, 레벨 70, 레슨 1
잠금
로그 추적 토큰
로그 추적 토큰
1
과제
Go SELF, 레벨 70, 레슨 1
잠금
명시적 데이터
명시적 데이터
1
과제
Go SELF, 레벨 70, 레슨 1
잠금
호출 시의 컨텍스트
호출 시의 컨텍스트
1
과제
Go SELF, 레벨 70, 레슨 1
잠금
컨텍스트를 재설정하지 마세요
컨텍스트를 재설정하지 마세요
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION