Maximize Throughput in a Serial Manufacturing Pipeline
Stacks & QueuesModel answerLast updated
Design and simulate a fixed-time serial pipeline to maximize completed units, given per-stage processing times, inter-stage buffer capacities, and blocking-after-service rules.
Serial Pipeline Throughput Simulation
Context
You are building a simulation engine for a turn-based factory game. The factory produces widgets through a series of stages that run in a fixed order. Your job is to figure out the best way to operate the line and, when upgrades are available, where to spend them.
Model
- There are
mstages numbered0throughm-1, run in strict series. - Stage
itakes exactlyp[i]seconds to process one widget. Each stage handles one widget at a time. - Between stage
iand stagei+1there is a FIFO queue with a maximum capacity ofb[i]widgets. - Blocking rule: when a stage finishes a widget but the downstream queue is full, the widget cannot leave. The stage stays blocked — it cannot accept new work — until a slot opens downstream.
- Raw materials are always available at stage 0.
- A widget counts as complete only if it exits stage
m-1at or before timeT.
Tasks
-
Explain your throughput strategy. How many widgets can the line produce in window
T? What limits it, and why do buffers matter only in certain conditions? -
Implement a simulator. Given
p,b, andT, return the number of completed widgets. -
Implement a greedy upgrade planner. Given a budget of
tokensupgrade credits, each of which multiplies one chosen stage's processing time by a factorspeedup < 1, allocate credits to maximize completed widgets. Use the simulator to evaluate each candidate upgrade.
What is expected
- State your assumptions and define the model concretely before writing code.
- Derive or state the closed-form count for the deterministic case and verify your simulator against it.
- Discuss when buffers matter and when they do not.
- Provide working Python code with correct handling of edge cases.
- Analyze time and space complexity.
Constraints
1 ≤ m ≤ 20p[i] > 0(floats allowed)b[i] ≥ 0; a value of 0 means no intermediate storage (pure blocking line)T > 01 ≤ tokens ≤ 10;0 < speedup < 1
Hints
Hint 1
The bottleneck — the stage with the largest p[i] — sets the steady-state rate once the pipeline is full. The first widget pays the full sum of all processing times before it exits. Use those two facts to write a closed-form formula and sanity-check your simulator against it.
Hint 2
Model each widget's journey with two recurrences: a start time (the max of when the widget arrived and when the stage last freed up) and a departure time (the max of finish time and when there is room downstream). The downstream-room constraint is what encodes the blocking rule.
Hint 3
For the upgrade planner, greedily try removing one token's worth of time from each stage, simulate the result, and pick the stage with the highest gain. Re-run the same loop after each upgrade, because the bottleneck can shift. When no stage improves output, break ties by upgrading whichever stage is currently slowest.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
1. Pin down the model before touching code
The line is serial with blocking-after-service. That means:
- A stage can start a new widget only after the previous widget has physically left for the downstream queue.
- A widget can leave a stage only when the downstream queue has an open slot.
These two rules, combined with FIFO within the line, give a complete and deterministic recurrence.
2. Throughput analysis
Steady-state rate equals 1 / max(p). No arrangement of buffers or release timing can beat this: the slowest stage is a hard ceiling.
First widget latency equals sum(p). The pipeline must fill end-to-end before any widget exits.
Closed-form count (deterministic, no blocking from zero-capacity buffers aside):
If T < sum(p): output = 0
Otherwise: output = floor((T - sum(p)) / max(p)) + 1
Use this to verify the simulator on simple cases.
When do buffers matter? With deterministic times they do not raise throughput — the formula above holds regardless of b. They matter the moment processing times become random (e.g., breakdowns, variable task sizes). Variability causes the bottleneck to sit idle waiting for upstream work, or to block waiting for downstream space. A buffer absorbs that variance and keeps the bottleneck running. The rule of thumb: size the buffers immediately before and after the bottleneck first, because every second the bottleneck is idle is permanently lost output.
Backpressure / release discipline: feeding raw materials faster than 1 / max(p) only piles up work-in-progress, fills queues, and blocks upstream stages. It does not add output. Release one unit every max(p) seconds at most.
3. Simulation recurrence
For widget n (0-indexed) at stage i:
start[n][i] = max(depart[n][i-1], depart[n-1][i])
(widget arrived) (stage is free)
finish[n][i] = start[n][i] + p[i]
depart[n][i] = max(finish[n][i], depart[n - b[i] - 1][i+1]) if i < m-1
= finish[n][i] if i == m-1
The departure constraint says: widget n can leave stage i only after widget n - b[i] - 1 has entered stage i+1, which frees one slot. When n < b[i] + 1 the downstream queue has room immediately and the constraint is inactive.
Process widgets in increasing n, and stages in increasing i within each widget. Every value needed is already computed.
Because departure times from the last stage are non-decreasing in n, the first widget that misses T ends the count.
4. Complexity
- Simulator: O(N · m) time, O(N · m) space, where
N ≤ T / min(p) + 1. Space can be reduced to O(m · max(b)) by keeping only the rows still needed for the departure constraint. - Upgrade planner: O(tokens · m · N · m) — for each token, try each stage, simulate, pick the best.
5. Edge cases
| Situation | Behavior |
|---|---|
T < sum(p) | 0 widgets finish |
b[i] = 0 everywhere | Pure blocking line; formula still holds |
| Multiple stages tie as bottleneck | Upgrading one does nothing; the planner must measure actual simulated gain, not just pick the slowest stage on paper |
Widget exits exactly at T | Counts (condition is ≤ T) |
p[i] ≤ 0 | Invalid input; raise immediately |
6. Python implementation
from typing import List, Optional
def simulate(p: List[float], b: List[int], T: float = 300.0) -> int:
"""
Return the number of widgets that exit the last stage by time T.
p[i] : processing time at stage i (must be > 0)
b[i] : buffer capacity between stage i and i+1 (len == len(p) - 1)
"""
m = len(p)
if m == 0:
raise ValueError("pipeline must have at least one stage")
if len(b) != m - 1:
raise ValueError("need exactly len(p) - 1 buffer capacities")
if any(t <= 0 for t in p):
raise ValueError("all processing times must be positive")
if any(cap < 0 for cap in b):
raise ValueError("buffer capacities must be non-negative")
# depart[n][i] = time widget n departs stage i
depart: List[List[float]] = []
n = 0
while True:
row = [0.0] * m
for i in range(m):
# widget must have arrived from stage i-1 (or be a raw input)
arrived = depart[n - 1][i] if n >= 1 else 0.0
# stage i must be free (previous widget has left)
prev_dep_here = depart[n - 1][i] if n >= 1 else 0.0
start = max(arrived if i == 0 else depart[n][i - 1],
prev_dep_here)
finish = start + p[i]
if i < m - 1:
# downstream slot constraint: need widget (n - b[i] - 1)
# to have entered stage i+1 before we can push into buffer
blocker = n - b[i] - 1
if blocker >= 0:
downstream_free = depart[blocker][i + 1]
else:
downstream_free = 0.0
row[i] = max(finish, downstream_free)
else:
row[i] = finish # last stage: depart == finish
# departure times from last stage are non-decreasing; stop here
if row[-1] > T:
return n
depart.append(row)
n += 1
def plan_upgrades(
p: List[float],
b: List[int],
tokens: int,
speedup: float = 0.8,
T: float = 300.0,
) -> List[float]:
"""
Greedily allocate upgrade tokens to maximize simulate(p, b, T).
Each token multiplies one stage's processing time by `speedup`.
Returns the final processing-time list.
"""
if not (0 < speedup < 1):
raise ValueError("speedup must be between 0 and 1 exclusive")
p = list(p) # work on a copy
for _ in range(tokens):
base = simulate(p, b, T)
best_stage: Optional[int] = None
best_output = base
for i in range(len(p)):
candidate = p[:i] + [p[i] * speedup] + p[i + 1:]
result = simulate(candidate, b, T)
# prefer higher output; break ties toward the current bottleneck
if result > best_output or (
result == best_output
and best_stage is not None
and p[i] > p[best_stage]
):
best_stage, best_output = i, result
if best_stage is None:
# no output gain from any stage; upgrade the bottleneck anyway
# to set up future gains
best_stage = max(range(len(p)), key=lambda j: p[j])
p[best_stage] *= speedup
return p
Sanity check:
simulate([30, 60, 45], [1, 1]) — bottleneck is stage 1 at 60 s, critical path is 135 s.
Closed form: floor((300 − 135) / 60) + 1 = 3. The simulator should return 3.
7. Common mistakes
- Conflating start time and arrival time. A widget can arrive at a stage but not start if the stage is still processing the previous widget. The
maxover both constraints is essential. - Ignoring the blocking departure rule. Omitting the
downstream_freeterm produces optimistic results that assume infinite buffers everywhere. - Upgrading on paper instead of by simulation. If two stages tie as the bottleneck, upgrading one does not improve throughput. Only the simulated delta reveals whether a token is worth spending.
- Forgetting the end-of-window cutoff. Starting a widget that cannot finish wastes in-game resources. In a real answer, mention that you would stop releasing raw material once
current_time + sum(p) > T.