We are designing a safe pause/resume mechanism for partial rollouts in a deployment pipeline.
The idea is to allow deployments to be paused and resumed at a later time, especially useful for partial rollouts (e.g., canary, blue-green) where we might want to pause to monitor metrics before proceeding.
Key requirements:
- The pipeline should be able to pause after a specific stage (or set of stages) and wait for a manual or automated signal to resume.
- It should be safe: if the pause is too long, we might want to have a timeout and then roll back or take some other action.
- The pause/resume mechanism should be integrated into the deployment pipeline without breaking the existing flow.
- We might want to have multiple pause points in a single rollout (e.g., after deploying to 10% of instances, then after 50%, etc.)
Steps:
Let's assume we are using a CI/CD tool that supports manual approvals and conditional steps. However, we want to design a more flexible system that can be integrated programmatically.
Design:
We can think of the rollout as a sequence of steps, each step being a deployment to a subset of infrastructure (partial rollout). After each step, we can have a pause.
The pause mechanism can be:
Option 1: Manual approval step in the pipeline.
- The pipeline stops at a stage and waits for a user to click "approve" to proceed.
- This is simple but requires human intervention.
Option 2: Automated pause with conditions (using metrics or tests).
- The pipeline pauses and runs a set of checks (e.g., monitoring metrics, smoke tests) and if they pass, it automatically resumes.
- If they fail, it can either wait (with a timeout) or roll back.
Option 3: Hybrid: we can have a manual approval that also runs automated checks, and the manual approver can see the results.
However, we are asked for a safe pause/resume, so we must consider:
- How to store the state of the pause? (so that if the pipeline system restarts, we can still resume)
- How to handle timeouts? (if we pause for too long, we might want to roll back)
Implementation:
Let's break down the pipeline stages:
- Deploy to canary (or a subset of instances) [Stage 1]
- Pause and wait for approval (or automated checks) [Pause 1]
- If approved (or checks pass), then proceed to next partial rollout (e.g., 25%) [Stage 2]
- Pause again [Pause 2]
- ... until 100%.
We can design a generic "Pause" stage that:
- Before pausing, it records the current state (e.g., which stage we are at, what percentage is deployed) in a persistent storage (like a database or a file in a shared storage).
- The pause stage then waits for a "resume" event. This event can be triggered by:
a) A manual action (via UI/CLI) that calls an API to resume.
b) An automated process that checks conditions and then calls the API.
- The pause stage also sets a timer (timeout). If the timeout is reached, it triggers a rollback (or another action).
How to integrate:
We can have a separate service (or use existing pipeline features) that handles the pause and resume.
Alternatively, we can design the pipeline to be stateful and have an external controller.
Let's assume we are using a pipeline tool that doesn't have built-in long-running pauses (like Jenkins, which has a input step but it's not designed for long pauses and state persistence).
Proposed design:
We'll have a "PauseController" that is responsible for:
- Storing the state of each deployment (deployment ID, current stage, timeout, etc.)
- Providing an API to pause (which the pipeline calls at the end of a stage) and to resume (which the pipeline or an external service calls).
The pipeline steps:
Step 1: Deploy to subset (e.g., 10%)
- After successful deployment, call PauseController.pause(deployment_id, stage=1, timeout=24h)
The pause method will:
- Record the state (deployment_id, stage, start_time, timeout) in a database.
- Then the pipeline step will wait (poll) for the state to change (to "resumed") or until timeout.
However, having the pipeline step wait for a long time (like 24h) might not be feasible because the pipeline runner might have timeouts or get restarted.
Alternative:
We break the pipeline into two parts:
Part 1: Up to the pause.
- The pipeline runs up to the pause point and then exits (with a success status?) but records that it is paused at a certain stage.
Then, we have a separate process (or a manual trigger) that resumes the pipeline from that stage.
But how do we resume? We need to know which stage to run next.
We can have a "resume" pipeline that is triggered by the PauseController (or by a user) and that resume pipeline will:
- Check the current state of the deployment (from the PauseController) and then run the next stage.
So the original pipeline stops after the pause point and the resume pipeline picks up from there.
This way, we don't have a long-running pipeline step.
Let's design the PauseController:
It has:
- A database table: deployment_pause_states
id (primary key)
deployment_id (string, unique for each rollout)
current_stage (integer, the stage that was just completed and we are pausing after)
paused_at (timestamp)
timeout_at (timestamp, calculated from paused_at + timeout)
status (enum: 'paused', 'resumed', 'timeout', 'rollback')
resumed_at (timestamp, when resumed)
resumed_by (string, who/what resumed)
- API endpoints:
POST /pause
body: { deployment_id: string, stage: integer, timeout_in_seconds: integer }
returns: { success: boolean, pause_id: string }
POST /resume
body: { deployment_id: string }
returns: { success: boolean }
GET /status/{deployment_id}
returns: the current state
- Also, a background process that checks for timeouts and marks them as timed out (and maybe triggers rollback?).
The pipeline:
Stage 1: Deploy to 10%
- If successful, call POST /pause with deployment_id and stage=1, timeout=86400 (24h)
Then the pipeline step ends (the pipeline runner exits, but we consider the pipeline up to stage1 as successful).
Later, when we want to resume:
- We call POST /resume with deployment_id.
Then we trigger a new pipeline (resume pipeline) that:
- Checks the status of the deployment (via GET /status) to see which stage we are at.
- Runs the next stage (stage 2: deploy to 25%).
And then after stage2, it will pause again (call pause again with stage=2).
So the resume pipeline is just like the original pipeline but starts from the next stage after the paused stage.
But note: the original pipeline and the resume pipeline are separate runs. We need to pass the deployment_id and the current stage.
Alternatively, we can have a single pipeline that is designed to be resumable:
The pipeline takes an argument: `start_stage` (default 1). And it runs from that stage until the end (or until the next pause).
Then, when we resume, we start the pipeline with start_stage = (last_paused_stage + 1).
However, we might have multiple pauses. So we need to know the next stage to run.
We can have the pause endpoint return the next stage? Or we can store the next stage in the pause state.
Let's adjust:
When we pause after stage N, we set current_stage = N and next_stage = N+1.
Then when we resume, we know to run stage (next_stage). And after that stage, we pause again (with stage = next_stage, and next_stage = next_stage+1).
But note: what if we want to skip a stage? We might not always want to run every stage. So maybe we don't store next_stage, but the resume pipeline checks the current_stage and then runs the stage that comes after that.
However, the pipeline definition might have a fixed set of stages. So we can have:
Stage 1: Deploy 10%
Stage 2: Deploy 25%
Stage 3: Deploy 50%
Stage 4: Deploy 100%
If we pause after stage 1, then we want to resume at stage 2.
So the resume pipeline should start at stage (current_stage + 1).
But what if we have conditional stages? Then the next stage might not be current_stage+1? We need to know the stage graph.
Alternatively, we can store the entire stage graph and the current position? That might be too complex.
Let's assume for simplicity that the stages are linear and numbered 1,2,3,...
Then:
In the pause state, we store the last completed stage (current_stage).
The resume pipeline will start at stage = current_stage + 1.
How does the resume pipeline know what to do for stage 2? It must have the same stage definitions.
So the pipeline definition (the code that defines the stages) must be the same for the original and the resume.
We can have a parameter that tells the pipeline from which stage to start.
Example:
Original pipeline run:
stage1 -> pause (current_stage=1)
Resume pipeline run:
start_stage=2
stage2 -> pause (current_stage=2)
But note: the pause after stage2 will set current_stage=2, and then the next resume will start at stage3.
So the pause state must be updated after each pause.
The PauseController:
When we pause after stage N, we set current_stage = N.
When we resume, we return the current_stage (so the resume pipeline knows to start at current_stage+1).
However, what if we want to resume and run multiple stages without pausing? We might want to skip a pause? Then we would need to have a way to mark a stage as "skip pause" or have a different condition.
Given the requirement is for partial rollouts, we probably want a pause after each partial step. So we assume each stage (except the last) has a pause.
But note: the last stage (100%) might not need a pause? Or we might want to pause after 100% to monitor? It depends.
Let's assume every stage (including the last) has a pause? Then after 100% we pause and then we can either mark the rollout as complete or roll back.
Alternatively, we can have the last stage not have a pause and just complete.
We can make the pause optional per stage? But then we need to know which stages have pauses.
Given the complexity, let's stick to:
We have a fixed set of stages, and after each stage (except the last) we pause.
How does the pipeline know which stages have pauses?
We can have a configuration that lists the stages that require a pause. Or we can have the pause step be part of the stage definition.
Another idea:
The pipeline is defined as:
stages:
- name: stage1
actions: [deploy_10%]
pause_after: true
- name: stage2
actions: [deploy_25%]
pause_after: true
...
Then the pipeline runs until it hits a stage with pause_after=true, then it pauses.
The pause state record would store the stage name (or index) that was just completed.
Then when resuming, we look for the next stage that has pause_after? Or we just run the next stage in order and then pause if that stage has pause_after?
Actually, we want to pause after the stage, so:
Run stage1 -> then pause (if stage1 has pause_after)
Then resume, run stage2 -> then pause (if stage2 has pause_after)
So the pause is after the stage.
In the pause state, we store the stage that was just completed (and we know that stage had pause_after).
Then when resuming, we run the next stage (by order in the list). We don't need to store next_stage because the stage list is fixed.
However, if we have conditional stages (like if condition X then run stage2a else stage2b) then the next stage is not fixed.
Given the complexity, let's assume linear stages for now.
So:
Pipeline definition (YAML):
stages:
- id: 1
name: Deploy 10%
script: ./deploy.sh 10
pause_after: true
- id: 2
name: Deploy 25%
script: ./deploy.sh 25
pause_after: true
- id: 3
name: Deploy 50%
script: ./deploy.sh 50
pause_after: true
- id: 4
name: Deploy 100%
script: ./deploy.sh 100
pause_after: false # no pause after last stage
The pipeline runs from stage X to stage Y, where X is the start_stage (default 1) and Y is the last stage (or until a pause).
Actually, we want to run until the next pause? But note: we might run multiple stages without pausing if we skip a pause? We don't have that.
We run one stage at a time and then pause if that stage has pause_after.
So the pipeline:
for stage in stages[start_stage:]:
run stage
if stage.pause_after:
pause and wait for resume (or timeout)
if timeout, then rollback and exit.
But we don't want to run the entire pipeline in one go because we want to pause after each stage with pause_after.
So we break the pipeline into:
Step 1: Run stage N (where N = start_stage)
Step 2: If stage N has pause_after, then pause.
Then we stop.
Then we resume and run stage N+1, and so on.
How do we break the pipeline?
We can have the pipeline run only one stage (the current stage) and then pause.
Then the resume pipeline runs the next stage.
So:
Original pipeline run (with start_stage=1):
- Run stage1
- Pause (because stage1.pause_after=true)
Resume pipeline (with start_stage=2):
- Run stage2
- Pause (because stage2.pause_after=true)
...
Until we run the last stage (which doesn't have pause_after) and then we are done.
How does the pause work?
After running stage N, we call PauseController.pause(deployment_id, stage_id=N, timeout=...)
Then the pipeline step ends (the pipeline runner exits). We consider the pipeline up to that point as successful.
The PauseController records:
deployment_id, current_stage = N, timeout_at = now+timeout, status='paused'
Then, when we want to resume, we call PauseController.resume(deployment_id). This will:
- Check if the deployment is in 'paused' state and not timed out.
- Update the state to 'resumed' and set resumed_at.
Then we trigger a new pipeline run with start_stage = N+1.
How does the resume process know which deployment_id to use?
We can pass the deployment_id as a parameter to the resume pipeline? Or we can have the PauseController trigger the pipeline?
Let's have the PauseController trigger the pipeline on resume? But then we need to know the pipeline configuration.
Alternatively, we can have a separate service that listens for resume events and then triggers the pipeline.
But to keep it simple, let's assume:
We have a way to trigger a pipeline run with parameters (like via API).
The resume process (manual or automated) will:
1. Call PauseController.resume(deployment_id)
2. Then trigger the pipeline with parameters: deployment_id and start_stage = (current_stage from PauseController) + 1.
But note: the PauseController.resume returns the current stage? We can return the next stage to run.
Alternatively, the resume process can:
- Get the current state (current_stage) from PauseController.
- Then trigger the pipeline with start_stage = current_stage + 1.
And then the pipeline will run from that stage.
How does the pipeline know the deployment_id?
The deployment_id should be the same for the entire rollout. We pass it as a parameter to every pipeline run.
So:
First pipeline run (start_stage=1) is triggered with deployment_id=XYZ.
After stage1, we pause with deployment_id=XYZ.
Then when resuming:
We call PauseController.resume(XYZ) -> returns current_stage=1 (the last completed stage).
Then we trigger the pipeline with deployment_id=XYZ and start_stage=2.
But wait: what if we have multiple pauses? The state after stage2 will have current_stage=2.
Then when we resume again, we get current_stage=2 and start_stage=3.
This works.
What about the timeout?
The PauseController has a background job that checks for paused deployments where timeout_at < now.
For those, it marks status='timeout' and then triggers a rollback? Or we let the next pipeline run check and see that it's timed out and then rollback?
We can have the background job also trigger a rollback pipeline? Or we can have the next pipeline run (when triggered) check the status and if it's timed out, then rollback and exit.
Let's do:
When the pause times out, the background job marks it as 'timeout'.
Then, when we try to resume (or when the next pipeline run starts), it checks the status:
if status is 'timeout', then run rollback steps and exit.
But note: the pause might time out and we don't want to proceed. So we should not allow resuming a timed out deployment.
Alternatively, the background job can trigger a rollback immediately.
Let's have:
The background job marks as 'timeout' and then triggers a rollback pipeline (with the deployment_id).
Then, if someone tries to resume a timed out deployment, we reject it.
What about the rollback?
We need a way to rollback the partial rollout. This is a separate process.
We can have a rollback pipeline that:
- Takes the deployment_id and rolls back to the previous stable state (or to 0%).
But note: we might have deployed 10% and then paused. If we timeout, we want to rollback that 10%.
So the rollback pipeline should know how to rollback from the current state (which we can get from the PauseController: current_stage tells us how much we deployed?).
Actually, the current_stage is the stage we last completed. So if we are at stage1 (10%), then we want to rollback from 10% to 0%.
We can have a mapping from stage to the percentage deployed? Or we can store the percentage in the pause state.
Let's adjust the pause state:
We store:
deployment_id
current_stage (the stage that was just completed, and we are paused after it)
deployed_percentage (the percentage that was deployed in that stage)
Then the rollback pipeline can use the deployed_percentage to know what to rollback.
But note: the stage might not directly map to percentage? It could be a set of actions.
Alternatively, we can store the desired state (the target percentage) after each stage.
Since we are doing partial rollouts, each stage sets a target percentage. So:
stage1: target=10%
stage2: target=25%
...
So when we pause after stage1, the current target is 10%. We want to rollback to 0%.
How do we know the previous target? We can store the previous target in the pause state? Or we know that the previous target is the one from the previous stage? But we don't have the previous stage in the state.
Alternatively, we can have the rollback pipeline:
- Get the current target from the pause state (which is the target of the last completed stage).
- Then rollback to the previous target. But we don't know the previous target.
We can store the entire history? Or we can assume that we rollback to 0%? That might not be safe if we have multiple partial rollouts and we want to rollback only the last one.
Given the complexity, let's assume:
We are only doing one rollout at a time? And we rollback to 0%? That might be too restrictive.
Alternatively, we can have the pipeline store the desired state (the target percentage) at each stage, and the rollback will set the target to the previous stage's target.
But we don't have the previous stage's target in the pause state.
We can store:
In the pause state, we store:
deployment_id
current_stage
current_target (the target percentage after this stage)
previous_target (the target percentage before this stage)
Then when we rollback, we set the target to previous_target.
How do we get previous_target?
When we run stage N (with target T_N), we know the previous target T_{N-1}? Not necessarily, because the previous stage might have been done in a previous pipeline run.
We can have the pipeline pass the previous target? Or we can have the PauseController store the entire history of targets?
Alternatively, we can have the rollback process:
- Get the current target (from the pause state, which is the target after the last stage).
- Then set the target to the previous stable target. But we don't know what that is.
Given the time, let's simplify:
We assume that the rollback will always set the target to 0%? That might be acceptable for the first partial rollout, but not for subsequent.
Another idea: we store the desired state (the target percentage) in the deployment system (like in Kubernetes, we have the replica count). We can query the current desired state and then set it to the previous stage's desired state.
But we don't have the previous stage's desired state.
We can have the pipeline record the desired state after each stage in the PauseController? Then we can look up the previous stage's desired state.
Let's adjust the pause state to store:
deployment_id
stage_id
desired_state (the target percentage after this stage)
And then we also have a table of stages (with stage_id and target_percentage) so we can look up the previous stage's target.
Alternatively, we can have the pipeline pass the desired state to the pause call.
Let's change the pause API:
POST /pause
body: { deployment_id, stage_id, desired_state, timeout_in_seconds }
Then the pause state stores:
deployment_id, stage_id, desired_state, paused_at, timeout_at, status
Then the rollback can:
- Get the current pause state (for the deployment_id, the one with the highest stage_id? or the one that is currently paused?).
- Then get the previous stage's desired_state by looking up the stage table for stage_id = current_stage - 1.
- Then set the target to that previous desired_state.
But note: we might have skipped stages? Then current_stage-1 might not be the previous stage that was run? We are running linear stages, so it should be.
However, if we have conditional stages, then we might not have run stage2? But then we wouldn't have a pause state for stage2.
We are only pausing after stages that have pause_after. So if stage2 is conditional and we skipped it, then we wouldn't have a pause after stage1? Actually, we pause after stage1, then when we resume we run stage2 (if condition is met) and then pause if stage2 has pause_after.
But if stage2 is skipped, then we don't run it and we don't pause? Then the next stage we run is stage3? But then the pause state would be for stage1? And then when we run stage3, we would update the pause state to stage3? But we didn't run stage2.
This is getting complex.
Given the time, let's stick to linear stages without conditionals.
Summary of the design:
Components:
1. PauseController (service with API and database)
2. Deployment pipeline (that runs stages and calls PauseController)
3. Rollback pipeline (triggered by PauseController on timeout or manually)
Steps:
Setup:
- Create a deployment with a unique deployment_id.
- Define the stages (with stage_id, name, script, pause_after, target_percentage).
Run pipeline (start_stage=1):
For each stage from start_stage to end:
Run the stage (which sets the target to the stage's target_percentage).
If stage.pause_after:
Call PauseController.pause(deployment_id, stage_id, current_target, timeout)
The pause call will:
- Record the state (deployment_id, stage_id, desired_state=current_target, paused_at, timeout_at, status='paused')
- Then the pipeline step ends (the pipeline runner exits).
Resume:
Call PauseController.resume(deployment_id)
The resume call will:
- Check if the current state is 'paused' and not timed out.
- Update status to 'resumed' and set resumed_at.
- Return the current stage_id and desired_state (or just the current stage_id).
Then trigger the pipeline with start_stage = (current_stage_id + 1) and the same deployment_id.
Timeout:
Background job in PauseController checks for records where timeout_at < now and status='paused'.
For each:
- Update status to 'timeout'
- Trigger the rollback pipeline with deployment_id and the desired_state (the target that was set at the time of pause? or the current target?).
Rollback:
The rollback pipeline:
- Gets the current pause state for the deployment_id (the one with the highest stage_id? or the one that is timed out?).
- If timed out, then we want to rollback to the previous stage's target.
- How to get the previous stage's target?
We have the stage table. We can get the current stage's target (from the pause state) and then find the previous stage (by stage_id) and get its target.
But note: the previous stage might have been paused and then resumed? We are only storing the current pause state (the last pause). We don't have the history of all stages.
Alternatively, we can store the entire history of desired states in the pause state? Or we can have a separate table that records every stage run (with deployment_id, stage_id, desired_state, timestamp).
Given the complexity, let's assume:
We rollback to 0%? Or we rollback to the previous stage's target by looking up the stage table.
But what if we have run stage1 (10%) and then stage2 (25%) and then paused? Then we want to rollback from 25% to 10%? But we don't have 10% stored anywhere.
We can store in the pause state the previous_target? But we don't know the previous target when we pause.
Alternatively, we can have the rollback pipeline:
- Get the current target (from the pause state, which is the target after the last stage).
- Then set the target to the previous stage's target (by stage_id-1) from the stage table.
But what if we have skipped stages? Then stage_id-1 might not have been run.
Given the complexity, let's change the requirement: we only rollback to 0% on timeout? That might be too drastic.
Alternatively, we can have the pipeline record every desired state change in a separate table (deployment_state_history). Then we can get the previous desired state from that table.
Let's do:
We have a table: deployment_state_history
id
deployment_id
stage_id
desired_state
timestamp
Every time we run a stage (that changes the desired state), we record it.
Then, when we rollback, we get the current desired state (from the pause state) and then look in the history for the previous record (for the same deployment_id, with stage_id < current_stage_id, order by stage_id desc, limit 1) and use that desired_state.
This way, we don't need to store the previous target in the pause state.
- Then set the target to that previous desired_state.
- Then mark the deployment as rolled back? Or we might want to resume from there? We can have a new pause after rollback? Let's not.
- We just rollback and then we are done? Or we might want to pause after rollback? Probably not.
- So the rollback pipeline sets the target and then exits.
What if we want to manually rollback without timeout?
We can have a manual trigger that calls the rollback pipeline with deployment_id.
The rollback pipeline will do the same: get the current pause state, then get the previous desired state from history, and set the target.
This is getting complex.
Given the time, let's simplify:
We assume that after each stage, we pause and we store the desired state (target percentage) for that stage.
When we rollback (due to timeout or manual), we rollback to the previous stage's desired state.
We store every stage's desired state in a history table.
The rollback pipeline:
- Get the current pause state (for the deployment_id, the one that is paused or timed out).
- Get the previous desired state from the history table (for the same deployment_id, stage_id < current_stage_id, order by stage_id desc, limit 1).
- Set the target to that previous desired state.
- Then update the pause state? We might want to create a new pause state for the rollback? Or just leave the current one as timed out/rolled back.
Actually, after rollback, we might want to pause again? Or we just complete the rollout? Let's assume we don't pause after rollback.
But note: the rollback might be partial too? We are rolling back to the previous stage's target, which might be 10% (if we were at 25%). So we are not rolling back to 0% necessarily.
This seems acceptable.
However, what if we are at stage1 (10%) and we timeout? Then there is no previous stage? Then we rollback to 0%.
So:
If there is no previous stage in the history, then rollback to 0%.
Steps for rollback:
current_stage = get_current_stage(deployment_id) # from the pause state (the one that is paused or timed out)
previous_state = get_previous_state(deployment_id, current_stage)
if previous_state is None:
previous_state = 0%
set_target(previous_state)
Then we are done.
But note: the rollback might also fail? Then we might need to handle that.
We'll leave error handling out for simplicity.
Now, let's write the API for PauseController:
POST /pause
body: { deployment_id: string, stage_id: integer, desired_state: integer (percentage), timeout_in_seconds: integer }
returns: { success: boolean, pause_id: string? }
POST /resume
body: { deployment_id: string }
returns: { success: boolean, next_stage_id: integer? }
GET /status/{deployment_id}
returns: { deployment_id, current_stage_id, desired_state, status, paused_at, timeout_at, resumed_at, resumed_by }
Background job:
- Periodically check for paused deployments where timeout_at < now and status='paused'
- For each, set status='timeout' and then trigger the rollback pipeline (with deployment_id).
We also need to record the history:
Every time we pause, we record the desired_state in the history table.
But note: we might run a stage that doesn't pause? Then we don't record? We record every stage run? We can record every stage run in the history table, regardless of pause.
Let's change: every stage run (that changes the desired state) is recorded in the history table.
Then the rollback can always get the previous state from the history.
So we don't need to store the desired_state in the pause state? We do, because the pause state records the current desired state at the time of pause. But we can get that from the history (the latest record for that deployment_id). However, the history might have multiple records for the same stage? We record every stage run, so for a given deployment_id, we can get the history ordered by stage_id and then by timestamp.
But we are pausing after each stage, so the history should have one record per stage (for a deployment). So we can get the current desired state from the history (the latest record).
However, the pause state is the source of truth for the current stage and desired state? We can have:
Pause state: current_stage_id, status, etc.
History: deployment_id, stage_id, desired_state, timestamp.
Then we can get the current desired state by looking at the history for the current_stage_id? But note: the current_stage_id in the pause state is the stage that was just completed. So the desired state for that stage is in the history.
We can avoid storing desired_state in the pause state and just get it from the history? But then we need to query the history every time.
Let's store the desired_state in the pause state for quick access.
And also record in the history for rollback.
So:
When we run a stage (with stage_id and desired_state), we:
1. Deploy to desired_state.
2. Record in history: (deployment_id, stage_id, desired_state, timestamp)
3. If stage.pause_after, then call pause with deployment_id, stage_id, desired_state, timeout.
The pause call then stores:
deployment_id, stage_id, desired_state, paused_at, timeout_at, status='paused'
Note: the desired_state in the pause state is the same as in the history record for that stage.
Now, the rollback:
We have a deployment_id that is in 'timeout' status.
We get the current pause state (which has current_stage_id and desired_state).
Then we get the previous stage's desired_state from the history:
SELECT desired_state FROM deployment_state_history
WHERE deployment_id = ? AND stage_id < ?
ORDER BY stage_id DESC
LIMIT 1
If no record, then 0%.
Then set the target to that desired_state.
Then we are done.
But what about the pause state? After rollback, we don't have a pause? We just rollback and then the deployment is over? Or we might want to pause after rollback? Let's not.
We can mark the deployment as rolled back? We can update the pause state to status='rolled_back'? But we don't have that status.
Let's add a status 'rolled_back' and set it when we rollback.
Alternatively, we can have a separate table for rollbacks? Let's keep it simple:
After rollback, we update the pause state status to 'rolled_back'.
Then if someone tries to resume a rolled back deployment, we reject.
Now, what about the resume API?
It should only work if status is 'paused'.
It will set status='resumed' and set resumed_at.
Then the resume process (the one that called resume) will trigger the pipeline with start_stage = current_stage_id + 1.
But note: what if the rollback happened in between? Then the current_stage_id might be the one that was paused, but we rolled back. We don't want to resume from that stage.
Actually, if we rolled back, we don't resume. We are done.
So the resume API should check: if status is not 'paused', then fail.
And the background job (timeout) sets status='timeout' and then triggers rollback, which sets status='rolled_back'.
So the only status that can be resumed is 'paused'.
This seems safe.
Now, let's consider the case where we have multiple pauses and we resume multiple times.
Stage1: pause (stage_id=1, desired_state=10%)
Resume: start_stage=2
Stage2: pause (stage_id=2, desired_state=25%)
...
The history table will have:
deployment_id | stage_id | desired_state
XYZ | 1 | 10
XYZ | 2 | 25
If we timeout at stage2, then:
current pause state: stage_id=2, desired_state=25%
rollback to stage1's desired_state: 10%
Then we set the target to 10% and mark as rolled_back.
This is correct.
What if we want to rollback to 0% even if there is a previous stage? We don't support that with this design. But we can have a manual rollback that always rolls back to 0%? We can have a separate API for that.
But let's stick to the design.
Implementation details:
We need to implement:
- PauseController service (with API and database)
- Pipeline that:
- Takes parameters: deployment_id, start_stage
- Runs stages from start_stage until the end (or until a stage with pause_after? Actually, we run one stage at a time and then pause if that stage has pause_after).
How does the pipeline know which stage to run next?
We have a configuration (YAML) that lists all stages.
The pipeline script (in the CI/CD tool) will:
1. Read the configuration.
2. Find the stage with stage_id = start_stage.
3. Run that stage (which might be a script that sets the desired state).
4. Record in history: (deployment_id, stage_id, desired_state) -> we need to know the desired_state for that stage? It's in the stage configuration.
5. If stage.pause_after:
- Call PauseController.pause(deployment_id, stage_id, desired_state, timeout)
- Then exit the pipeline (with success).
6. If not, then go to the next stage (start_stage+1) and repeat.
But note: we are running only one stage per pipeline run? Because we want to pause after each stage that has pause_after.
So the pipeline should run only one stage and then pause.
Then the resume pipeline runs the next stage.
So the pipeline always runs exactly one stage (the one with stage_id = start_stage) and then pauses if that stage has pause_after.
But what if the stage does not have pause_after? Then we run it and then move to the next stage? But we are only running one stage per pipeline run.
We can have the pipeline run until it hits a stage that requires pause? But then we might run multiple stages in one pipeline run, which we don't want because we want to pause after each stage that requires pause.
Let's change:
The pipeline runs from start_stage and runs every stage until it either:
a) Runs a stage that has pause_after -> then pause and exit.
b) Runs the last stage (which doesn't have pause_after) -> then exit without pausing.
But then we might run multiple stages in one pipeline run (if the first stage doesn't have pause_after). That might be acceptable.
However, the requirement is for partial rollouts and we want to pause after each partial rollout. So we want a pause after each stage that changes the percentage? So we set pause_after=true for every stage that changes the percentage.
But what if we have a stage that doesn't change the percentage? Then we don't need to pause.
So the pipeline:
current_stage = start_stage
while current_stage <= last_stage:
run stage current_stage
record in history
if stage current_stage has pause_after:
call pause
exit (so we only run up to this stage)
else:
current_stage++
If we exit the loop without pausing, then we are done.
This way, we run as many stages as we want until we hit a pause.
But note: we might have a stage that doesn't have pause_after, then we run it and then the next stage might have pause_after. Then we run two stages in one pipeline run.
Example:
Stage1: pause_after=false
Stage2: pause_after=true
Pipeline start_stage=1:
Run stage1 (no pause)
Run stage2 (has pause, so pause after stage2)
Then we pause with stage_id=2.
This is acceptable.
However, if we want to pause after every stage that changes the percentage, then we set pause_after=true for all stages that change the percentage.
So if stage1 changes the percentage, we set pause_after=true.
Then we would run stage1 and pause, then resume and run stage2 and pause, etc.
But with the above loop, if stage1 has pause_after, we run stage1 and then pause, and we don't run stage2 until next resume.
That's what we want.
So the pipeline logic:
stages = load_stages_from_config() # list of stages, each with id, script, pause_after, desired_state (or we compute desired_state from the script? We assume the stage config has desired_state)
current_stage_id = start_stage
while current_stage_id <= max_stage_id:
stage = get_stage_by_id(current_stage_id)
# Run the stage (which sets the desired_state)
run(stage.script) # this should set the desired_state to stage.desired_state
# Record in history
insert into deployment_state_history (deployment_id, stage_id, desired_state) values (deployment_id, current_stage_id, stage.desired_state)
if stage.pause_after:
# Pause
response = PauseController.pause(deployment_id, current_stage_id, stage.desired_state, timeout)
if not response.success:
# Handle error? Maybe fail the pipeline?
exit(1)
else:
exit(0) # exit the pipeline, we are paused
else:
current_stage_id += 1
# If we exit the loop, we are done (no pause after the last stage)
But note: what if we have a stage that fails? Then we don't record in history and we don't pause? We should fail the pipeline.
Now, the resume process:
After we call PauseController.resume(deployment_id), we get the current_stage_id (the one that was paused).
Then we trigger the pipeline with start_stage = current_stage_id + 1.
What if the current_stage_id is the last stage? Then start_stage would be beyond the last stage? We should check:
If current_stage_id is the last stage, then we don't need to run another stage? But note: the last stage doesn't have pause_after, so we wouldn't have paused after the last stage.
So we only pause after stages that have pause_after, and the last stage doesn't have pause_after, so we won't pause after the last stage.
Therefore, if we are paused, then current_stage_id is not the last stage.
So when we resume, we run the next stage.
This seems consistent.
Now, what about the rollback pipeline?
It is triggered by:
- Timeout (by background job)
- Manual trigger (by user)
The rollback pipeline:
Steps:
1. Get the deployment_id (from the trigger or from the environment).
2. Get the current pause state for the deployment_id. If there is no pause state, or if the status is not 'paused' or 'timeout', then exit (or fail).
3. If status is 'timeout', then we are doing an automatic rollback.
If status is 'paused', then we are doing a manual rollback.
4. Get the current_stage_id and current_desired_state from the pause state.
5. Get the previous desired_state from the history:
SELECT desired_state FROM deployment_state_history
WHERE deployment_id = ? AND stage_id < ?
ORDER BY stage_id DESC
LIMIT 1
If no record, then previous_desired_state = 0.
6. Set the desired_state to previous_desired_state (by running the rollback script? Or by calling an API of the deployment system?).
We assume we have a way to set the desired_state (like updating a Kubernetes deployment).
7. Update the pause state: status='rolled_back', rolled_back_at=now.
8. Exit.
Note: we don't record the rollback in the history? We could, but then we would have a stage for rollback? We don't have a stage for rollback.
Alternatively, we can treat the rollback as a stage? But it's not in the original stage list.
We can record in the history with stage_id = -1 or something? Or we can have a separate table for rollbacks.
Let's not record in the history for now.
This design is quite complex but covers the requirements.
However, we haven't considered:
- What if the pause times out and we rollback, but then we want to resume from the rollback state? We don't support that. We mark as rolled_back and that's it.
- What if we want to pause after rollback? We don't.
Given the time, we'll stop here.
Let's summarize the steps:
Setup:
- Create deployment_id (e.g., UUID).
- Define stages (with stage_id, script, pause_after, desired_state).
Run pipeline (with start_stage):
For stage from start_stage:
Run stage.script (which sets the desired_state to stage.desired_state)
Record in history: (deployment_id, stage_id, desired_state)
If stage.pause_after:
Call PauseController.pause(deployment_id, stage_id, desired_state, timeout)
Then exit pipeline.
Else:
Continue to next stage.
If we finish all stages, then pipeline exits (success).
Resume:
Call PauseController.resume(deployment_id) -> returns current_stage_id.
Then run pipeline with start_stage = current_stage_id + 1.
Timeout:
Background job marks pause state as 'timeout' and triggers rollback pipeline.
Rollback:
Get current pause state (must be 'paused' or 'timeout').
Get previous desired_state from history (stage_id < current_stage_id, order by stage_id desc, limit 1). If none, 0.
Set desired_state to previous_desired_state.
Update pause state to 'rolled_back'.
This design assumes:
- The stages are linear and we have a fixed set of stages.
- Each stage has a desired_state (the target percentage) and a flag pause_after.
- The deployment system (Kubernetes, etc.) can set the desired_state (like replica count) and we assume that setting the desired_state is idempotent and safe.
We also assume that the pipeline and the PauseController are in the same network and can call each other.
This is a high-level design. We haven't considered:
- Error handling in the pipeline (if the stage fails, we should not pause and we should fail the pipeline).
- How to handle multiple deployments at the same time? The deployment_id should be unique.
We'll leave it at that.
Let's write the database schema:
Table: deployment_pause_states
id (primary key)
deployment_id (string, unique? Not necessarily, because we might have multiple pauses for the same deployment? But we only have one active pause per deployment? We are pausing after each stage, so we update the same record? Or we create a new record for each pause?
We are pausing after each stage, so we want to record the current stage. We can update the same record (for the deployment) every time we pause? But then we lose the history of previous pauses? We don't need the history of pauses, we only need the current pause state.
So we can have one record per deployment in deployment_pause_states.
But what if we have multiple deployments? Then we have multiple records.
So:
deployment_pause_states:
deployment_id (primary key) # one record per deployment
current_stage_id
desired_state
paused_at
timeout_at
status
resumed_at
resumed_by
rolled_back_at
But note: when we resume, we don't delete the record, we update the current_stage_id? Actually, we don't update the current_stage_id in the pause state when we resume? We update the status to 'resumed' and then when we run the next stage, we will update the current_stage_id when we pause again? Or we don't update until the next pause?
Let's think:
After stage1, we pause: current_stage_id=1.
Then we resume: status becomes 'resumed'. But we don't change current_stage_id? Then when we run stage2 and then pause again, we update the current_stage_id to 2.
So the current_stage_id in the pause state is the last stage that was paused (or timed out, or rolled back). It doesn't change on resume.
Then when we run the next stage (stage2), we update the current_stage_id to 2 when we pause again.
But what if we rollback? We set status='rolled_back' and we don't change current_stage_id? We leave it as the stage that caused the rollback? That's okay.
So the current_stage_id is the stage that was last paused (or timed out, or rolled back). It doesn't change on resume.
Then, when we resume, we use the current_stage_id to determine the next stage (current_stage_id+1).
But note: if we rollback, we set the desired_state to the previous state, but we don't change the current_stage_id? We leave it as the stage that was paused? That might be confusing.
Alternatively, when we rollback, we set current_stage_id to the stage that we rolled back to? But we don't have a stage for rollback.
Let's not change current_stage_id on rollback. It remains the stage that was paused (the one that we rolled back from).
Then if we try to resume after rollback? We shouldn't be able to because status is 'rolled_back'.
So it's okay.
Now, the history table:
deployment_state_history:
id (primary key)
deployment_id
stage_id
desired_state
timestamp
We record every stage run (even if the stage doesn't have pause_after? Yes, because we want to know the history of desired states.
But note: if we run stage1 and stage2 in one pipeline run (because stage1 doesn't have pause_after), then we record both stage1 and stage2 in the history.
Then if we pause after stage2, the pause state will have current_stage_id=2 and desired_state=stage2.desired_state.
Then if we rollback, we get the previous desired_state from the history (stage1.desired_state).
This works.
One more thing: the timeout.
We set timeout_at when we pause.
The background job checks for paused records where timeout_at < now.
But note: what if we resume before timeout? Then we set resumed_at and status='resumed'. Then the background job will ignore it.
So we are good.
Now, let's write the steps in code for the pipeline:
Pseudocode for the pipeline:
deployment_id = get from environment or parameter
start_stage = get from parameter (default 1)
stages = load_stages() # from config file
current_stage_id = start_stage
while current_stage_id <= max_stage_id:
stage = stages.get(current_stage_id)
# Run the stage
run(stage.script) # this should set the desired_state to stage.desired_state
# Record in history
db.insert_history(deployment_id, current_stage_id, stage.desired_state)
if stage.pause_after:
# Pause
response = http.post(PauseController.pause_url, json={
'deployment_id': deployment_id,
'stage_id': current_stage_id,
'desired_state': stage.desired_state,
'timeout_in_seconds': 86400 # or from config?
})
if response.status != 200:
raise Exception("Pause failed")
else:
print("Paused. Exiting pipeline.")
exit(0)
else:
current_stage_id += 1
print("All stages completed without pause.")
exit(0)
The resume process:
We have a deployment_id that we want to resume.
Step 1: Call PauseController.resume(deployment_id)
Step 2: Get the current_stage_id from the response (or from the pause state after resume).
Step 3: Trigger the pipeline with start_stage = current_stage_id + 1 and the same deployment_id.
The rollback pipeline:
deployment_id = get from trigger
pause_state = PauseController.get_status(deployment_id)
if pause_state.status not in ['paused', 'timeout']:
exit(1) # cannot rollback
# Get previous desired_state
previous = db.query("""
SELECT desired_state FROM deployment_state_history
WHERE deployment_id = ? AND stage_id < ?
ORDER BY stage_id DESC
LIMIT 1
""", deployment_id, pause_state.current_stage_id)
if previous:
desired_state = previous[0].desired_state
else:
desired_state = 0
# Set the desired_state (this is deployment specific)
set_desired_state(deployment_id, desired_state)
# Update pause state
PauseController.mark_rolled_back(deployment_id)
This is a high-level design.
We haven't considered:
- How to handle the case where the stage script fails? We should not pause and we should fail the pipeline.
- How to handle the case where the pause API fails? We should fail the pipeline.
- How to handle the case where the rollback fails? We should retry? We don't handle that.
But for a design, this should be acceptable.
Let me know if you have any questions.</think>
I'll design a comprehensive safe pause/resume deployment pipeline for partial rollouts (canary/blue-green) with safety guards and state management.
Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Deployment │────▶│ State Store │────▶│ Orchestrator │
│ Pipeline │ │ (DB/Redis/etc) │ │ (Controller) │
└─────────────────┘ └──────────────────┘ └────────┬────────┘
│ │ │
│ ┌────▼────┐ ┌────▼────┐
│ │Paused │ │Resume │
└───────────────────▶│States │◀─────────────│Signal │
└─────────┘ └─────────┘
1. Core Components
A. State Store (Single Source of Truth)
-- PostgreSQL Schema Example
CREATE TABLE rollout_states (
rollout_id UUID PRIMARY KEY,
deployment_id VARCHAR(255),
current_stage INTEGER NOT NULL,
total_stages INTEGER NOT NULL,
status VARCHAR(50) NOT NULL, -- 'ACTIVE', 'PAUSED', 'RESUMED', 'COMPLETED', 'ROLLED_BACK'
paused_at TIMESTAMPTZ,
pause_reason TEXT,
resume_deadline TIMESTAMPTZ,
metadata JSONB,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE stage_metrics (
id SERIAL PRIMARY KEY,
rollout_id UUID REFERENCES rollout_states(rollout_id),
stage INTEGER NOT NULL,
success_count INTEGER DEFAULT 0,
failure_count INTEGER DEFAULT 0,
error_rate DECIMAL(5,2),
latency_p95 INTEGER,
custom_checks JSONB,
last_checked TIMESTAMPTZ
);
B. Orchestrator/Controller Service
# Pseudocode for Controller
class RolloutController:
def __init__(self, state_store, metric_monitor):
self.state_store = state_store
self.monitor = metric_monitor
def execute_stage(self, rollout_id, stage_num):
"""Execute a rollout stage with safety checks"""
state = self.state_store.get(rollout_id)
# 1. Pre-execution validation
if not self._validate_stage_execution(state, stage_num):
return {"status": "blocked", "reason": "pre-check_failed"}
# 2. Execute partial deployment (e.g., 10% traffic)
result = self._deploy_partial(state.deployment_id, stage_num)
# 3. Record metrics
self._record_stage_metrics(rollout_id, stage_num, result)
# 4. Determine if should pause
if self._should_pause_after_stage(state, stage_num):
self._pause_rollout(rollout_id, stage_num, "AUTOMATED_PAUSE")
return {"status": "paused", "next_stage": stage_num + 1}
return {"status": "advanced", "next_stage": stage_num + 1}
def pause_rollout(self, rollout_id, reason, manual=True):
"""Manual or automated pause with safety checks"""
state = self.state_store.get(rollout_id)
# Safety: Check if already paused/completed
if state.status in ['PAUSED', 'COMPLETED', 'ROLLED_BACK']:
raise InvalidStateError(f"Cannot pause {state.status} rollout")
# Safety: Check pause cooldown (prevent rapid pause/resume)
if self._is_in_cooldown(state):
raise CooldownError("Rollout in cooldown period")
# Record pause
self.state_store.update(
rollout_id,
status='PAUSED',
paused_at=datetime.utcnow(),
pause_reason=reason,
resume_deadline=datetime.utcnow() + timedelta(hours=24) # Auto-timeout
)
# Trigger alerts
self._alert_pause(rollout_id, reason)
def resume_rollout(self, rollout_id, approver=None):
"""Resume with validation"""
state = self.state_store.get(rollout_id)
# 1. Validate resumable state
if state.status != 'PAUSED':
raise InvalidStateError(f"Cannot resume {state.status} rollout")
# 2. Check if resume deadline passed (auto-rollback scenario)
if state.resume_deadline < datetime.utcnow():
self._auto_rollback(rollout_id, "resume_deadline_exceeded")
return {"status": "auto_rolled_back"}
# 3. Safety: Pre-resume health checks
health_status = self.monitor.check_health(state.deployment_id)
if not health_status.healthy:
raise HealthCheckFailedError(f"Health check failed: {health_status.issues}")
# 4. Record resume
self.state_store.update(
rollout_id,
status='RESUMED',
resumed_at=datetime.utcnow(),
resumed_by=approver
)
return {"status": "resumed", "next_stage": state.current_stage + 1}
2. Safety Mechanisms
A. Automatic Pause Triggers
pause_triggers:
- error_rate: > 5% # Error rate threshold
- latency_p95: > 2000ms # Latency threshold
- success_rate: < 95% # Success rate threshold
- custom_checks: # Custom business logic
- "feature_a_conversion_rate_drop > 20%"
- "payment_failure_rate_increase > 10%"
- time_based: # Night/weekend pauses
- "hour in [0, 6]" # Auto-pause 12AM-6AM
- manual_approval_required: # Always pause for certain stages
- stages: [3, 5] # Stages 3 and 5 always need approval
B. Timeout & Auto-Rollback
class TimeoutManager:
def __init__(self, state_store, controller):
self.state_store = state_store
self.controller = controller
def check_paused_rollouts(self):
"""Cron job every 5 minutes"""
paused_rollouts = self.state_store.query(
"SELECT * FROM rollout_states "
"WHERE status = 'PAUSED' "
"AND resume_deadline < NOW()"
)
for rollout in paused_rollouts:
# Check if conditions improved since pause
if self._conditions_improved(rollout):
self._auto_resume(rollout.rollout_id)
else:
self.controller.auto_rollback(
rollout.rollout_id,
reason="pause_timeout_without_improvement"
)
def _conditions_improved(self, rollout):
"""Check if metrics improved since pause"""
current_metrics = self.monitor.get_current_metrics(rollout.deployment_id)
paused_metrics = rollout.metadata.get('metrics_at_pause')
return (
current_metrics.error_rate < paused_metrics.error_rate * 0.8 and
current_metrics.latency_p95 < paused_metrics.latency_p95 * 0.9
)
C. Approval Workflow
class ApprovalWorkflow:
REQUIRED_APPROVERS = ["tech_lead", "sre", "product_manager"]
def request_approval(self, rollout_id, stage_num, context):
"""Create approval request with context"""
approval_id = self._create_approval_record(
rollout_id=rollout_id,
stage=stage_num,
required_approvers=self.REQUIRED_APPROVERS,
context={
"metrics": self._get_stage_metrics(rollout_id, stage_num),
"stage_percentage": self._get_stage_percentage(stage_num),
"rollback_plan": self._get_rollback_plan(rollout_id),
"estimated_duration": "2 hours"
}
)
# Notify approvers via Slack/Email
self._notify_approvers(approval_id)
return approval_id
def check_approvals(self, approval_id):
"""Check if all required approvals received"""
approvals = self.state_store.get_approvals(approval_id)
if len(approvals) >= len(self.REQUIRED_APPROVERS):
# All approved, proceed
self._record_approval(approval_id)
return True
# Check if any rejection
if any(a.decision == 'REJECTED' for a in approvals):
return False # Will trigger rollback
return None # Still pending
3. Pipeline Integration Examples
A. GitHub Actions / GitLab CI
# .github/workflows/partial-rollout.yml
name: Partial Rollout with Pause
on:
workflow_dispatch:
inputs:
rollout_id:
description: 'Rollout ID'
required: true
start_stage:
description: 'Stage to start from (1-based)'
required: false
default: 1
jobs:
deploy-stage:
runs-on: ubuntu-latest
steps:
- name: Check current rollout state
run: |
STATE=$(curl -s $CONTROLLER_API/rollouts/${{ inputs.rollout_id }}/status)
CURRENT_STAGE=$(echo $STATE | jq -r .current_stage)
if [ $CURRENT_STAGE -ge ${{ inputs.start_stage }} ]; then
echo "Stage $CURRENT_STAGE already completed"
exit 0
fi
- name: Execute stage ${{ inputs.start_stage }}
run: |
./scripts/deploy-stage.sh ${{ inputs.rollout_id }} ${{ inputs.start_stage }}
- name: Check auto-pause conditions
id: pause_check
run: |
METRICS=$(curl -s $MONITOR_API/deployments/${{ inputs.rollout_id }}/metrics)
ERROR_RATE=$(echo $METRICS | jq -r .error_rate)
if (( $(echo "$ERROR_RATE > 0.05" | bc -l) )); then
echo "pause=true" >> $GITHUB_OUTPUT
echo "reason=error_rate_high" >> $GITHUB_OUTPUT
else
echo "pause=false" >> $GITHUB_OUTPUT
fi
- name: Pause if needed
if: steps.pause_check.outputs.pause == 'true'
run: |
curl -X POST $CONTROLLER_API/rollouts/${{ inputs.rollout_id }}/pause \
-H "Content-Type: application/json" \
-d '{"reason": "${{ steps.pause_check.outputs.reason }}", "manual": false}'
# Send notification
./scripts/notify-pause.sh ${{ inputs.rollout_id }}
# Exit with special code to pause pipeline
exit 42 # Custom pause exit code
- name: Proceed to next stage
if: steps.pause_check.outputs.pause != 'true' || failure()
run: |
echo "Proceeding to next stage..."
# Trigger next stage
gh workflow run partial-rollout.yml \
-f rollout_id=${{ inputs.rollout_id }} \
-f start_stage=$(( ${{ inputs.start_stage }} + 1 ))
B. Kubernetes Operator Pattern
# rollout_operator.py
class RolloutOperator:
def reconcile(self, rollout_cr):
"""Reconcile Custom Resource for rollout"""
state = self.state_store.get(rollout_cr.spec.rollout_id)
if state.status == 'PAUSED':
# Check for resume signal
if self._has_resume_signal(rollout_cr):
self.controller.resume_rollout(rollout_cr.spec.rollout_id)
return
if state.status in ['ACTIVE', 'RESUMED']:
next_stage = state.current_stage + 1
# Execute next stage
result = self.controller.execute_stage(
rollout_cr.spec.rollout_id,
next_stage
)
# Update CR status
rollout_cr.status.status = result['status']
rollout_cr.status.currentStage = next_stage
rollout_cr.status.lastUpdate = datetime.utcnow()
if result['status'] == 'paused':
rollout_cr.status.pauseReason = result.get('reason')
rollout_cr.status.pausedAt = datetime.utcnow()
4. Safety Features Implementation
A. Circuit Breaker Pattern
class CircuitBreaker:
def __init__(self, failure_threshold=5, recovery_timeout=300):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.failure_count = 0
self.last_failure_time = None
self.state = 'CLOSED' # CLOSED, OPEN, HALF_OPEN
def before_stage_execution(self, rollout_id):
"""Check if circuit is open"""
if self.state == 'OPEN':
time_since_failure = time.time() - self.last_failure_time
if time_since_failure > self.recovery_timeout:
self.state = 'HALF_OPEN'
return True
return False # Circuit open, block execution
return True
def after_stage_execution(self, success):
"""Update circuit state based on result"""
if success:
self.failure_count = 0
if self.state == 'HALF_OPEN':
self.state = 'CLOSED'
else:
self.failure_count += 1
self.last_failure_time = time.time()
if self.failure_count >= self.failure_threshold:
self.state = 'OPEN'
B. Safe Rollback Strategy
class SafeRollback:
def __init__(self, state_store):
self.state_store = state_store
def execute_rollback(self, rollout_id, reason):
"""Gradual rollback (reverse of rollout)"""
state = self.state_store.get(rollout_id)
# 1. Get rollback stages (reverse order)
rollback_stages = self._get_rollback_stages(state.current_stage)
for stage in reversed(rollback_stages):
# 2. For each stage, reverse the deployment
self._reverse_stage(rollout_id, stage)
# 3. Pause after each rollback stage
if stage > 1: # Don't pause after final rollback to 0%
self.state_store.update_pause(
rollout_id,
stage,
f"ROLLBACK_STEP_{stage}",
paused_at=datetime.utcnow()
)
self._wait_for_resume_or_timeout(rollout_id)
# 4. Mark as rolled back
self.state_store.update_status(rollout_id, 'ROLLED_BACK', reason)
5. Monitoring & Alerting
A. Rollout Dashboard Metrics
# Prometheus metrics
rollout_status{rollout_id="abc123",status="paused"} 1
rollout_stage_progress{rollout_id="abc123",stage="3",target="25%"} 0.25
rollout_pause_duration_seconds{rollout_id="abc123",reason="error_rate"} 3600
rollout_approval_pending_seconds{rollout_id="abc123"} 1800
B. Alert Rules
alert_rules:
- alert: RolloutPausedTooLong
expr: rollout_pause_duration_seconds > 86400 # 24 hours
for: 5m
labels:
severity: critical
annotations:
summary: "Rollout {{ $labels.rollout_id }} paused for >24h"
- alert: RolloutApprovalStuck
expr: rollout_approval_pending_seconds > 7200 # 2 hours
for: 10m
labels:
severity: warning
6. CLI/API Interface
# CLI Commands
rollout-cli pause --id=abc123 --reason="high_error_rate" --deadline="2024-01-20T00:00:00Z"
rollout-cli resume --id=abc123 --approver="john@example.com"
rollout-cli status --id=abc123
rollout-cli rollback --id=abc123 --reason="business_decision"
# API Endpoints
POST /api/v1/rollouts/{id}/pause
POST /api/v1/rollouts/{id}/resume
GET /api/v1/rollouts/{id}/status
POST /api/v1/rollouts/{id}/rollback
GET /api/v1/rollouts/{id}/metrics
7. Disaster Recovery & Audit
-- Audit table
CREATE TABLE rollout_audit_log (
id BIGSERIAL PRIMARY KEY,
rollout_id UUID,
action VARCHAR(50), -- PAUSE, RESUME, ROLLBACK, STAGE_COMPLETE
actor VARCHAR(255), -- user or system
reason TEXT,
previous_state JSONB,
new_state JSONB,
created_at TIMESTAMPTZ DEFAULT NOW()
);
-- Point-in-time recovery: Reconstruct rollout state from audit log
8. Best Practices & Recommendations
- Rate Limiting: Implement rate limiting on pause/resume operations to prevent thrashing
- Sticky Sessions: Ensure user sessions aren't broken during pauses (use consistent hashing)
- Database Locks: Use advisory locks in PostgreSQL to prevent concurrent modifications
- Idempotency: All operations should be idempotent (same request twice = same result)
- Backfill: Support backfilling historical data for existing deployments
- Testing: Chaos engineering tests for pause/resume scenarios
- Documentation: Auto-generated runbooks from pause reasons
- Access Control: RBAC for pause/resume/rollback permissions
9. Example Rollout Flow
Stage 1 (10% traffic) → ✅ Success → Auto-pause (monitor 5 min)
Stage 2 (25% traffic) → ⏸ Manual approval required
├─ Approver reviews metrics
├─ Checks rollback plan
└─ Approves → Resume → Stage 3 (50% traffic)
Stage 3 (50% traffic) → ⚠️ Error rate spikes → Auto-pause
├─ Alert sent to team
├─ 30 min investigation
└─ Manual rollback triggered → Gradual rollback to 0%
This design provides:
- Safety: Multiple guardrails (auto-pauses, timeouts, health checks)
- Transparency: Complete audit trail and real-time visibility
- Flexibility: Manual/automated pauses, configurable thresholds
- Recovery: Safe rollback strategies and timeout handling
- Integration: Works with any CI/CD system via API/CLI
The key insight is treating pause/resume as first-class operations with persistent state, rather than ad-hoc pipeline stops, enabling safe partial rollouts at any scale.