Backend Go DevOps • 12 min read

Building a CI/CD Runner: Docker Backend Deep Dive

Hoang Dang Tan Phat (Kane)

Hoang Dang Tan Phat (Kane)

Nov 17, 2026

Buller is a proof of concept for a GitHub Actions-style job system. Users submit a YAML workflow, and a worker runs its shell steps and streams the logs to a web UI. The runner executes commands it does not control, so it has to stream output while they run, enforce limits, and clean up after timeouts and failures. Most of the difficulty sits in how the runner talks to Docker. This post covers the architecture, the job queue, the backend interface, the Docker exec protocol, and three bugs we fixed.

Table of Contents

  • Architecture Overview
  • PostgreSQL as Job Queue
  • Backend Interface Design
  • Docker Exec Protocol Internals
  • Bug Fixes That Matter
  • Security & Isolation
  • Conclusion

Architecture Overview

The control plane is a Fiber REST API. It accepts jobs, serves status, and streams logs to the browser over Server-Sent Events. Runners are separate processes that claim jobs from PostgreSQL and execute them. The control plane never calls a runner directly, so all coordination goes through the database.

flowchart LR
  U["curl / Web UI"] -->|"REST and SSE"| CP["Control Plane<br/>Fiber API"]
  CP -->|"INSERT / SELECT"| DB[("PostgreSQL<br/>jobs, job_logs")]
  DB -.->|"NOTIFY job_queue_channel"| RN["Runner workers"]
  RN -->|"ClaimJob (SKIP LOCKED)"| DB
  RN -->|"INSERT job_logs"| DB
  RN -->|"Docker Engine API"| JC["Job container<br/>one per job"]

Each runner processes one job at a time. A job is claimed, gets a workspace directory and a network, runs its steps in a container, and is torn down before the final status is written.

PostgreSQL as Job Queue

We used the jobs table as the queue instead of a message broker. The table already holds the state a queue needs: status, priority, lease, and attempt count. A broker would add a service to run, and it would split the truth between two systems. A job could be committed without its message, or a message could go out for an insert that rolled back.

PostgreSQL covers three queue needs: wake-up, atomic claiming, and liveness.

Wake-up with NOTIFY. A trigger fires on each insert of a queued job and calls pg_notify('job_queue_channel', ...). Each runner holds one connection that runs LISTEN on that channel. Notifications are not stored, so a runner that is not listening at that moment never sees one. The runner therefore also polls: after each claim attempt it waits up to 60 seconds for a notification, and it sleeps 5 seconds if none arrives.

Atomic claiming with SKIP LOCKED. ClaimJob selects the next queued job and updates it in one statement:

UPDATE jobs
SET status = 'running', attempt = attempt + 1, runner_id = $1,
    lease_until = now() + $2::interval
WHERE id = (
  SELECT id FROM jobs
  WHERE status = 'queued' AND scheduled_at <= now()
  ORDER BY priority DESC, created_at ASC
  FOR UPDATE SKIP LOCKED
  LIMIT 1
)
RETURNING *;

SKIP LOCKED lets each runner skip rows another transaction has locked. Two runners never claim the same job, and neither one waits on the other.

Leases for liveness. A claim sets lease_until to 60 seconds ahead. The worker’s startHeartbeat goroutine sends a heartbeat every 30 seconds. The Heartbeat query updates the row only when id, runner_id, and attempt still match, so a stale attempt cannot renew a lease it no longer owns.

Two gaps remain, and they matter before you copy this pattern.

  1. The Heartbeat query is declared :exec in sqlc, so it does not report rows affected. A runner that lost its lease gets no error and keeps running. The worker logs a warning only when the query itself fails.
  2. Nothing reclaims a job whose lease has expired. RequeueJob runs only in the worker’s failure branch. If a runner crashes mid-job, the row stays running indefinitely. A reaper that requeues rows with status = 'running' AND lease_until < now() would close this. It is not written yet.

Backend Interface Design

The worker should not know whether a job runs in Docker or in a Kubernetes pod. It hands a claimed job to a backend and receives success or failure back:

type Backend interface {
    Execute(ctx context.Context, job *models.Job, workflow *models.Workflow) error
    Name() string
    Close() error
}

The backend owns everything between claim and teardown. The worker writes the final job status based only on the returned error.

classDiagram
  class Backend {
    <<interface>>
    +Execute(ctx, job, workflow) error
    +Name() string
    +Close() error
  }
  class DockerBackend {
    +Execute(ctx, job, workflow) error
  }
  class KubernetesBackend {
    <<planned>>
  }
  class Worker {
    -backend Backend
    +claimAndExecute(ctx) error
  }
  Backend <|.. DockerBackend
  Backend <|.. KubernetesBackend
  Worker --> Backend

NewBackend is the only place that switches on the configured type. It returns a DockerBackend for "docker". For "kubernetes" it returns an error, so the runner fails at startup rather than accepting jobs it cannot run.

switch backendType {
case "docker":
    return docker.NewDockerBackend(db, dockerCfg, logger)
case "kubernetes":
    return nil, fmt.Errorf("kubernetes backend not yet implemented")
default:
    return nil, fmt.Errorf("unknown backend type: %s", backendType)
}

A Kubernetes backend would create a pod, run each step through the pod exec API, and delete the pod in cleanup. The worker, queue, log streaming, and status updates would stay the same. steps.Executor takes any StepRunner, so a Kubernetes step runner plugs in there. The Docker config type stays inside internal/runner/backend/docker, so shared code never imports Docker types.

Per job, DockerBackend.Execute does the following:

  1. Creates /tmp/buller/jobs/{id} on the host.
  2. Creates a bridge network named buller-job-{id}.
  3. Pulls the image if it is missing locally.
  4. Creates and starts a container that runs sleep infinity.
  5. Runs each step with docker exec.
  6. Runs cleanup in a deferred function, whether the job succeeded or failed.

The container runs sleep infinity because steps are not its main process. Each step attaches a new exec session, so the workspace and installed tools carry over between steps. The network has to be attached at container creation: Docker will not connect a container created with NetworkMode: none to a bridge later, so buildHostConfig passes the network name in directly.

Docker Exec Protocol Internals

docker exec looks like one call, but it is a protocol with four phases. The step runner in internal/runner/backend/docker/step_runner.go implements each one.

sequenceDiagram
  participant R as Step runner
  participant D as Docker daemon
  participant P as Process in container
  R->>D: POST /containers/{id}/exec (Create)
  D-->>R: exec ID
  R->>D: POST /exec/{id}/start (Attach, Upgrade: tcp)
  D-->>R: 101 Switching Protocols, raw TCP stream
  D->>P: fork /bin/sh -c "step command"
  loop until the process exits
    P-->>D: stdout / stderr bytes
    D-->>R: framed chunks (8-byte header + payload)
  end
  D-->>R: EOF (connection closes)
  R->>D: GET /exec/{id}/json (Inspect)
  D-->>R: ExitCode

Phase 1: Create Exec Instance

ContainerExecCreate sends the command, environment, and working directory. It runs nothing yet and returns an exec ID for the next calls.

execConfig := types.ExecConfig{
    Cmd:          []string{"/bin/sh", "-c", stepCtx.Step.Run},
    WorkingDir:   "/workspace",
    Env:          envVars,
    AttachStdout: true,
    AttachStderr: true,
    Tty:          false,
}
execResp, err := r.client.ContainerExecCreate(ctx, r.containerID, execConfig)

Tty is false on purpose. With a TTY, the daemon merges stdout and stderr into one stream, and the step runner could no longer tell them apart. Running through /bin/sh -c lets a step use pipes, &&, and redirects.

Phase 2: Hijacked Connection

ContainerExecAttach is where the protocol turns unusual. The client sends an HTTP upgrade to the exec start endpoint. The daemon replies 101 Switching Protocols, and from then on the socket carries the raw process output rather than HTTP. The Docker SDK calls this a hijacked connection. The HTTP client gives up the socket, and the step runner reads it directly.

Because the socket is hijacked, cancelling the request context does not close it. The step runner handles that itself:

go func() {
    select {
    case <-ctx.Done():
        attachResp.Close()
    case <-execDone:
    }
}()

Closing the socket also unblocks the demultiplexing goroutine. Without that close, the goroutine would wait on a read that a long-running command does not end on its own.

Phase 3: Multiplexed Stream Format

For a non-TTY exec, the daemon prefixes each chunk with an 8-byte header. The first byte names the stream, and the last four bytes give the payload size as a big-endian uint32:

flowchart LR
  subgraph Frame["One frame on the wire"]
    direction LR
    H["Header: 8 bytes"]
    P["Payload: N bytes"]
  end
  H --> H0["Byte 0: stream type<br/>0 stdin, 1 stdout, 2 stderr"]
  H --> H1["Bytes 1-3: padding (zero)"]
  H --> H2["Bytes 4-7: payload size<br/>big-endian uint32"]
  P --> P0["Raw bytes of stdout or stderr"]

Frames repeat until the daemon closes the connection, and stdout and stderr frames interleave in write order. Parsing this by hand means reading exactly 8 bytes, decoding the size, then reading exactly that many bytes. A short read in the middle of a frame drops data. The Docker SDK’s stdcopy package does this correctly:

_, err := stdcopy.StdCopy(stdoutWriter, stderrWriter, attachResp.Reader)

StdCopy writes stream 1 payloads to stdoutWriter and stream 2 payloads to stderrWriter. The step runner gives each stream its own io.Pipe, and a StreamLine goroutine reads each pipe. When StdCopy returns, the runner closes both writers so the readers see EOF.

Phase 4: Exit Code Retrieval

The exit code is not part of the stream. After the stream ends, the step runner calls ContainerExecInspect:

inspectResp, err := r.client.ContainerExecInspect(ctx, execResp.ID)
return &steps.StepResult{ExitCode: inspectResp.ExitCode}, nil

Inspect runs after the stream ends because the stream ends when the process exits. The step executor then checks ExitCode != 0 and stops the job at the first failing step.

Bug Fixes That Matter

Bugs #1 and #2 were in the pre-Docker executor at internal/runner/executor.go, which ran commands with os/exec. Their fixes now live in internal/runner/steps. Bug #3 only exists in the Docker path, because the pre-Docker executor had no container cleanup.

Bug #1: The 64KB Line Trap

The original code read output with bufio.Scanner (internal/runner/executor.go:139):

scanner := bufio.NewScanner(reader)
for scanner.Scan() {
    line := scanner.Text()
    // append to log batch
}

bufio.Scanner caps each token at 64KB. A longer line makes Scan() return false and ends the loop. The error is in scanner.Err(), which the original code never checked.

The output pipe is also the problem. The command was read through cmd.StdoutPipe(), and nothing drains the pipe after the scanner stops. Once the kernel pipe buffer fills, the child blocks on its next write, and the step hangs until the job timeout kills it. This is a hang that looks like a slow step, not a short log. The repo has no reproduction for it, so the mechanism is reasoned from the code.

The fix replaces the scanner with bufio.Reader.ReadString('\n'), which grows its buffer until it finds a newline (internal/runner/steps/logger.go:50):

bufReader := bufio.NewReader(reader)
for {
    line, err := bufReader.ReadString('\n')
    line = strings.TrimSuffix(line, "\n")
    if line != "" {
        // append to log batch
    }
    if err != nil {
        break // io.EOF or a real read error
    }
}

The trade-off is memory. A single very long line stays in the runner’s memory until its newline arrives. The job container’s memory limit does not cover the runner process, and Buller does not cap line length yet.

Bug #2: Silent Step Syndrome

The original code flushed logs inside the scan loop (internal/runner/executor.go:164-167):

for scanner.Scan() {
    // ...append line...
    select {
    case <-ticker.C:
        e.flushLogs(ctx)
    default:
    }
}

The check runs only when a new line arrives. A step that prints nothing never reaches it, so its batch sits in memory. A step that runs sleep 60 looks frozen in the UI and then dumps all its lines when it ends.

The fix moves flushing into its own goroutine with an independent ticker (internal/runner/steps/logger.go:93-106):

func (ls *LogStreamer) StartFlusher(ctx context.Context) {
    ls.wg.Add(1)
    go func() {
        defer ls.wg.Done()
        ticker := time.NewTicker(time.Duration(ls.config.FlushInterval) * time.Second)
        defer ticker.Stop()
        for {
            select {
            case <-ctx.Done():
                return
            case <-ls.stopCh:
                return
            case <-ticker.C:
                ls.Flush(ctx)
            }
        }
    }()
}

FlushInterval defaults to one second. ExecuteSteps starts the flusher once per job and defers a final Flush, so the last batch is written even when the job fails.

Bug #3: Cleanup Apocalypse

A job that exceeds its timeout cancels its context. If cleanup reuses that context, every call fails at once with context canceled. The container, its network, and the workspace are left behind. The fix lives in internal/runner/backend/docker/cleanup.go:31:

cleanupCtx, cancel := context.WithTimeout(context.Background(), cleanupTimeout)
defer cancel()
cli.ContainerStop(cleanupCtx, containerID, container.StopOptions{Timeout: &timeout})
cli.ContainerRemove(cleanupCtx, containerID, types.ContainerRemoveOptions{Force: true})
removeJobNetwork(cleanupCtx, cli, networkID, logger)
os.RemoveAll(workspaceDir)

The repo has no pre-fix container cleanup to diff, so this failure is reasoned from how context cancellation works. It is not reproduced in a test.

cleanupTimeout is two minutes. Without a bound, a wedged Docker daemon would hang the worker, and no later job could start.

The hijacked read needs a different fix, shown in Phase 2. Cleanup needs a context that stays alive, while the read needs an explicit close when the context ends.

Security by Default

Workflow steps run arbitrary shell commands, so the container is the security boundary. buildHostConfig in internal/runner/backend/docker/resources.go sets:

  • CapDrop: ["ALL"] removes every Linux capability. The job can read and write its mounted workspace and run ordinary programs, but it cannot change file ownership or bind privileged ports.
  • SecurityOpt: ["no-new-privileges"] stops setuid binaries from gaining privileges during exec.
  • Seccomp is not set in code, so Docker’s default profile applies.
  • Per-job network. Each job gets its own bridge network, buller-job-{id}, which is removed during cleanup. Jobs cannot reach each other’s containers.
  • No auto-remove. AutoRemove is false, so cleanup removes the container explicitly.

The per-job network is not an egress policy. A job can still reach the internet through the bridge. Running a job with no network would need --network none, which Buller does not expose yet.

Resource Isolation That Works

Three limits come from the runner’s config, and each maps to a field in buildHostConfig:

LimitDefaultEnv varDocker field
CPU2.0 coresBULLER_DOCKER_CPUSNanoCPUs
Memory2 GBBULLER_DOCKER_MEMORY_GBMemory
Processes1024BULLER_DOCKER_PIDS_LIMITPidsLimit

The CPU value is converted to nanoseconds per second, so 2.0 becomes 2_000_000_000, and Docker enforces it through the cgroup CPU quota. The memory limit is a standard Docker feature. When a container exceeds it, the kernel OOM killer terminates a process in the container, and the container’s exec step ends with a non-zero status. Buller then reports the step as failed. The repo does not include an OOM test, so treat this as standard Docker behavior rather than something Buller verifies.

The PID limit is the one most people forget. Without it, a fork bomb in a step can exhaust the host’s process table and affect other containers on the same daemon. With PidsLimit set, forks fail inside the job container.

Lessons Learned

  1. Docker exec is a protocol, not a call. It is create, a hijacked stream, then a separate inspect for the exit code. Each phase has its own failure mode.
  2. Hijacked connections need manual cancellation. A context does not close them. A goroutine that closes the connection on ctx.Done() does.
  3. LISTEN/NOTIFY works for a small queue. Notifications are not durable, so pair them with polling and SKIP LOCKED, and you avoid running another service.
  4. Cleanup needs its own context. A cleanup that reuses a cancelled context leaves resources behind in exactly the cases where cleanup matters.
  5. bufio.Scanner has a 64KB limit. Its error comes from Err(), not from the loop, so a loop that ignores it stops reading without warning.

Conclusion

Buller runs each job in its own container with its own network, executes steps through docker exec, streams logs as they arrive, and tears everything down on every exit path. The backend interface keeps the worker unchanged, so a Kubernetes backend would replace only Execute.

Two gaps remain: expired leases are never reclaimed, and the heartbeat cannot detect a lost lease. Fixing the reaper comes first. The Kubernetes backend is planned, and NewBackend rejects it at startup until it exists.

To try Buller, run docker-compose up -d, enqueue a job with the curl example in the project README, and watch its logs stream in the web UI. Issues and pull requests are welcome, especially for the reaper.

docker ci-cd golang architecture postgres docker-exec job-queue containerization
Hoang Dang Tan Phat (Kane)

Hoang Dang Tan Phat (Kane)

Full-stack developer with 8+ years experience. Building scalable systems with Go, TypeScript, and React.