Skip to content

Global Context

Ductwork provides a key-value store that persists across all steps in a pipeline. Unlike return values, which flow from one step to the next, global context is accessible from any step at any point in the pipeline’s execution.

Return value passing works well for linear data flow, but some information needs to be available everywhere:

  • User or request identifiers: set once at the start and used throughout
  • Configuration fetched early: lookup results that several later steps need
  • Sidecar data: values you need that don’t really fit as data flow
  • Cross-cutting concerns: tracing IDs, feature flags, or tenant context

Global context lets you get at this data without passing it through every step’s return value.

Access global context through the context object, which is in-scope in every step. Be sure to use string keys:

# Write a value
context.set("user_id", 123)
# Read it back
context.get("user_id") #=> 123

Values can be any JSON serializable Ruby object: strings, numbers, hashes, or arrays.

To keep shared state under control, context keys are write-once by default. Trying to overwrite an existing key raises an error:

context.set("user_id", 1)
context.set("user_id", 2) #=> raises Ductwork::Context::OverwriteError

This prevents accidental overwrites and makes it easier to tell where a value came from.

When you really do need to update a value, pass overwrite: true:

context.set("user_id", 1)
context.set("user_id", 2, overwrite: true) # succeeds
context.get("user_id") #=> 2

Use this sparingly. If you find yourself overwriting a lot, consider whether the data would fit better as step return values or in a dedicated accumulator.

Reads and writes to global context are atomic, meaning each operation finishes before another can start. You won’t get torn reads or partial writes.

That doesn’t make concurrent access safe in every case, though:

# Step A and Step B run concurrently
# Both try to set "status" at the same time
# Step A
context.set("status", "processing", overwrite: true)
# Step B
context.set("status", "validating", overwrite: true)
# Final value depends on execution order!

⚠️ Caution: Avoid writing to the same key from concurrent steps. Even with atomic operations, the final value depends on execution order. If concurrent steps need to share state, use separate keys or coordinate through step dependencies.

A common pattern is setting a trace ID at the start of a pipeline so every step can log it:

class InitializeTracing < Ductwork::Step
def execute
trace_id = SecureRandom.uuid
context.set("trace_id", trace_id)
# trace_id is now available in all subsequent steps
end
end
class ProcessOrder < Ductwork::Step
def execute
trace_id = context.get("trace_id")
Rails.logger.info("[#{trace_id}] Processing order #{order.id}")
# ... process order
end
end