---
title: Context as First Argument
impact: MEDIUM
impactDescription: follows Go idiomatic patterns for cancellation and timeouts
tags: go, context, patterns, quality
---

## Context as First Argument

`context.Context` should always be the first parameter of a function, typically named `ctx`. This consistency makes it easy to propagate cancellation, deadlines, and markers across call stacks.

**Incorrect (wrong order or missing):**

```go
func (s *Service) FetchUser(userID string, ctx context.Context) (*User, error) {
    // ctx is second argument
    return s.repo.Get(ctx, userID)
}

func ProcessTask(taskID string) {
    // Missing context for potentially long-running operation
    db.Exec("UPDATE tasks SET status = 'done' WHERE id = ?", taskID)
}
```

**Correct (context first):**

```go
func (s *Service) FetchUser(ctx context.Context, userID string) (*User, error) {
    return s.repo.Get(ctx, userID)
}

func ProcessTask(ctx context.Context, taskID string) error {
    return db.ExecContext(ctx, "UPDATE tasks SET status = 'done' WHERE id = ?", taskID)
}
```

**Benefits:**
- Standardizes API signatures across the codebase
- Simplifies cancellation propagation
- Enables proper timeout handling for I/O and external calls
- Improves observability with trace IDs in context

**Tools:** golangci-lint, contextcheck
