Bus Factor Remediation with AWS Transform Custom
Use AWS Transform custom to analyze codebases and generate structured documentation from undocumented business rules, architecture decisions, and tribal knowledge before it walks out the door.
From Tribal Knowledge to Living Docs: The Bus Factor Remediation Playbook
Your architect just put in their two weeks. They are the only person who knows why the payment service retries exactly three times. They know what the
legacy_flags field means on the user model. They can explain why half the cron jobs exist. In two weeks, that context walks out the door.This is the bus factor problem. And it hits harder than most teams expect.
You cannot prevent people from leaving. But you can prevent the knowledge loss. AWS Transform custom (ATX) can analyze your codebase and extract the business logic, architecture decisions, and dependencies into structured documentation. Even after the person is gone.
This post walks through the playbook. Real commands, real output, real sample code.
What Is Bus Factor and Why Traditional Fixes Fail
Bus factor measures how many people can leave a team before a system becomes unmaintainable. If only one person understands a critical service, your bus factor is one. That is a serious operational risk.
The typical response is to schedule knowledge transfer sessions. Write docs in Confluence. Do exit interviews. The problem is these approaches capture maybe 10% of what actually matters. The person being interviewed does not remember every decision they made over three years. They forget the edge cases. They skip things that feel obvious to them but are not obvious to anyone else.
The real knowledge lives in the code itself. Naming conventions that encode business rules. Error handling that reflects production incidents from two years ago. Config values that exist because of a specific customer escalation. Magic numbers with no comments. Retry logic that was added at 2am during an outage.
If the knowledge is in the code, use a tool that can read code.
AWS Transform Custom in 30 Seconds
AWS Transform custom is an agentic AI service built for code modernization and transformation at scale. You define what you want in natural language. ATX analyzes code and produces structured output.
Most people know it for version upgrades and SDK migrations. Upgrading Python 3.8 to 3.13. Migrating boto2 to boto3. Moving from Log4J to SLF4J. But the custom transformation engine works for any code to artifact workflow. Including documentation generation.
The workflow is:
- Define a transformation in natural language
- Test it on a sample repo
- Publish it to your account
- Run it across one repo or hundreds
The CLI is called
atx . Transformations are reusable once defined. The agent learns from each execution and gets better when run repeatedly against similar codebases.
The Sample Codebase
For this walkthrough, I have a small payment processing service with three modules. Each one contains tribal knowledge that only the original author would understand without digging.
Module 1: Payment Processor
Handles charge requests with fraud checking, gateway calls, and ledger writes.
# payment_processor.py
import timeimport requestsfrom datetime import datetime, timedelta
RETRY_COUNT = 3RETRY_DELAY = 2.0GATEWAY_URL = "https://payments.internal/v2/charge"DAILY_LIMIT = 50000FRAUD_THRESHOLD = 0.82
def process_payment(user_id: str, amount: float, currency: str) -> dict: """Process a payment for the given user.""" if amount > DAILY_LIMIT: raise ValueError(f"Amount {amount} exceeds daily limit")
fraud_score = _check_fraud(user_id, amount) if fraud_score > FRAUD_THRESHOLD: return {"status": "blocked", "reason": "fraud_check_failed"}
# Retry logic added after Q3 2023 gateway instability incident for attempt in range(RETRY_COUNT): try: response = _call_gateway(user_id, amount, currency) if response["status"] == "success": _update_ledger(user_id, amount, currency) return response except requests.Timeout: if attempt < RETRY_COUNT - 1: time.sleep(RETRY_DELAY * (attempt + 1)) else: return {"status": "failed", "reason": "gateway_timeout"}
return {"status": "failed", "reason": "max_retries_exceeded"}
def _check_fraud(user_id: str, amount: float) -> float: """Score from internal fraud ML model. Threshold 0.82 set by risk team Jan 2024.""" response = requests.post( "https://fraud.internal/v1/score", json={"user_id": user_id, "amount": amount}, timeout=5, ) return response.json()["score"]
def _call_gateway(user_id: str, amount: float, currency: str) -> dict: """POST to payment gateway v2. Migrated from v1 in March 2023.""" response = requests.post( GATEWAY_URL, json={ "user_id": user_id, "amount": amount, "currency": currency, "timestamp": datetime.utcnow().isoformat(), }, timeout=10, ) return response.json()
def _update_ledger(user_id: str, amount: float, currency: str): """Write to financial ledger. Must happen after gateway confirms.""" requests.post( "https://ledger.internal/v1/entries", json={ "user_id": user_id, "amount": amount, "currency": currency, "type": "charge", "timestamp": datetime.utcnow().isoformat(), }, timeout=5, )Module 2: User Limits
Enforces per-user daily and monthly spending caps with tier-based logic.
# user_limits.py
from datetime import datetime, timedeltafrom typing import Optional
# Tier limits set by finance team, reviewed quarterlyTIER_LIMITS = { "free": {"daily": 500, "monthly": 5000}, "starter": {"daily": 5000, "monthly": 50000}, "business": {"daily": 50000, "monthly": 500000}, "enterprise": {"daily": 500000, "monthly": 5000000},}
# Grace period: users who just upgraded get 24h at old limits# to avoid blocking transactions during tier propagation delayUPGRADE_GRACE_HOURS = 24
def check_user_limit( user_id: str, amount: float, user_tier: str, tier_changed_at: Optional[datetime] = None,) -> dict: """Check if transaction is within user's spending limits.""" effective_tier = _resolve_effective_tier(user_tier, tier_changed_at) limits = TIER_LIMITS.get(effective_tier)
if limits is None: # Unknown tier defaults to most restrictive. Safety decision from Jan 2023. limits = TIER_LIMITS["free"]
daily_spent = _get_daily_spend(user_id) monthly_spent = _get_monthly_spend(user_id)
if daily_spent + amount > limits["daily"]: return { "allowed": False, "reason": "daily_limit_exceeded", "limit": limits["daily"], "spent": daily_spent, }
if monthly_spent + amount > limits["monthly"]: return { "allowed": False, "reason": "monthly_limit_exceeded", "limit": limits["monthly"], "spent": monthly_spent, }
return {"allowed": True}
def _resolve_effective_tier( user_tier: str, tier_changed_at: Optional[datetime]) -> str: """During grace period after upgrade, use previous tier to avoid blocking.""" if tier_changed_at is None: return user_tier
grace_deadline = tier_changed_at + timedelta(hours=UPGRADE_GRACE_HOURS) if datetime.utcnow() < grace_deadline: return user_tier
return user_tierModule 3: Notification Router
Routes payment notifications to different channels based on rules that came from audits, cost decisions, and customer complaints.
# notification_router.py
from enum import Enumfrom typing import Optional
class NotificationChannel(Enum): EMAIL = "email" SMS = "sms" PUSH = "push" SLACK_OPS = "slack_ops"
# Amounts above this trigger ops team notification# Set during SOC2 audit Q2 2023, risk team requires immediate visibilityOPS_ALERT_THRESHOLD = 10000
# SMS disabled for amounts under $100 to reduce costs# Product decision from Aug 2023 after Twilio bill spikeSMS_MINIMUM_AMOUNT = 100
# Rate limit: max 3 notifications per user per hour# Added after customer complaint about notification spam, ticket INC-4521RATE_LIMIT_PER_HOUR = 3
def route_notification( user_id: str, event_type: str, amount: float, user_preferences: Optional[dict] = None,) -> list[str]: """Determine which channels to notify for a payment event.""" channels = []
# Always send email for payment events (compliance requirement) channels.append(NotificationChannel.EMAIL.value)
# Push notification unless user opted out if user_preferences and user_preferences.get("push_enabled", True): channels.append(NotificationChannel.PUSH.value)
# SMS only for larger transactions to control costs if amount >= SMS_MINIMUM_AMOUNT: if user_preferences and user_preferences.get("sms_enabled", False): channels.append(NotificationChannel.SMS.value)
# Ops team alert for high value transactions if amount >= OPS_ALERT_THRESHOLD: channels.append(NotificationChannel.SLACK_OPS.value)
# Failed payments always go to ops regardless of amount if event_type == "payment_failed": if NotificationChannel.SLACK_OPS.value not in channels: channels.append(NotificationChannel.SLACK_OPS.value)
return _apply_rate_limit(user_id, channels)
def _apply_rate_limit(user_id: str, channels: list[str]) -> list[str]: """Drop user-facing notifications if rate limit exceeded. Ops notifications are never rate limited (safety decision). """ recent_count = _get_recent_notification_count(user_id)
if recent_count >= RATE_LIMIT_PER_HOUR: return [c for c in channels if c == NotificationChannel.SLACK_OPS.value]
return channels
def _get_recent_notification_count(user_id: str) -> int: """Count notifications sent to user in the last hour. Uses Redis TTL keys.""" passLook at these three files from the perspective of a new hire. You can read the code and understand what it does mechanically. But you cannot understand why. Why three retries? Why 0.82? Why does unknown tier default to free instead of raising an error? Why is SMS disabled under $100? The code works, but the reasoning is invisible.
The Playbook: Extract Knowledge with ATX
Step 1: Create a Custom Transformation Definition
Launch ATX in interactive mode:
atxTell the agent what you want:
I want to create a custom transformation that analyzes a Python codebase andgenerates documentation covering:1. Business rules and their rationale (thresholds, limits, validation logic)2. Integration dependencies (external services, APIs, databases)3. Error handling patterns and retry strategies4. Historical context embedded in comments or naming conventions5. Architecture decisions that are implicit in the code structure6. Risk areas where knowledge is concentrated in one person or one file
Output should be a structured markdown file per module, plus a system-levelsummary showing cross-cutting concerns and dependencies between modules.ATX generates a transformation definition with phases:
Generated transformation definition: "tribal-knowledge-extraction"
Phase 1 - Discovery: Scan all Python files, identify modules and their roles, map import relationships Phase 2 - Business Rule Extraction: Identify constants, thresholds, limits, and conditional logic. Extract surrounding comments and docstrings for rationale. Phase 3 - Dependency Mapping: Trace all external service calls (HTTP, database, message queue). Document endpoints, timeouts, and failure modes. Phase 4 - Pattern Analysis: Identify error handling strategies, retry logic, fallback behaviors, and rate limiting patterns. Phase 5 - Documentation Generation: Produce per-module markdown with extracted knowledge organized into business rules, dependencies, decisions, and historical context. Phase 6 - System Summary: Generate cross-module view showing how modules interact, shared dependencies, and concentrated risk areas. Phase 7 - Validation: Verify generated docs reference actual code locations and that all identified business rules map to specific lines.Save and publish the transformation:
save a draft with name "tribal-knowledge-extraction" and description"Analyze Python codebases to extract undocumented business rules, integrationdependencies, and architectural decisions into structured documentation"atx custom def publish --name "tribal-knowledge-extraction"Step 2: Run the Transformation
Apply the transformation to the payment service:
atx custom run --name "tribal-knowledge-extraction" --path ./payment-serviceATX processes each file, traces dependencies across modules, and builds the documentation.
Step 3: Review the Generated Documentation
Here is what ATX produces.
Payment Processor module:
# Payment Processor: Extracted Knowledge
## Business Rules
| Rule | Value | Rationale | Source ||------|-------|-----------|--------|| Daily transaction limit | $50,000 | Compliance requirement | DAILY_LIMIT constant || Fraud score threshold | 0.82 | Set by risk team, Jan 2024 (prev. 0.75, too many false positives) | FRAUD_THRESHOLD constant || Gateway retry count | 3 | Added after Q3 2023 gateway instability incident | RETRY_COUNT constant || Retry backoff strategy | Linear, 2s base (2s, 4s, 6s) | Prevents thundering herd on gateway recovery | RETRY_DELAY usage pattern |
## Integration Dependencies
- **Payment Gateway v2** (payments.internal/v2/charge) - Method: POST - Timeout: 10s - Migrated from v1 in March 2023 - Failure mode: Timeout triggers retry loop
- **Fraud Scoring Service** (fraud.internal/v1/score) - Method: POST - Timeout: 5s - Returns float score [0, 1] - Failure mode: Exception propagates (no retry)
- **Financial Ledger** (ledger.internal/v1/entries) - Method: POST - Timeout: 5s - Write-after-confirm pattern only - Failure mode: Silent (fire and forget, no error handling)
## Error Handling
- Gateway timeouts: Retry up to 3x with linear backoff. After exhausting retries, return failure dict. Does not raise exception to caller.- Fraud check failure: Blocks transaction immediately. No retry.- Amount over limit: Raises ValueError. Caller expected to handle.- Ledger write failure: Not handled. Potential data consistency risk.
## Architectural Decisions
- Ledger writes are post-confirmation only (not pre-authorized). A gateway success without ledger write is possible if process crashes between the two calls. No compensation mechanism exists.- Fraud check happens before gateway call to avoid charging users who would be blocked anyway (cost optimization).- All calls are synchronous and blocking. No async processing.
## Risk Areas
- Ledger write has no error handling. If it fails silently, the charge went through but is not recorded.- No circuit breaker on gateway calls. If gateway is down, each request takes 30s (3 retries x 10s timeout) before failing.User Limits module:
# User Limits: Extracted Knowledge
## Business Rules
| Rule | Value | Rationale | Source ||------|-------|-----------|--------|| Free tier daily limit | $500 | Finance team, reviewed quarterly | TIER_LIMITS dict || Starter tier daily limit | $5,000 | Finance team, reviewed quarterly | TIER_LIMITS dict || Business tier daily limit | $50,000 | Finance team, reviewed quarterly | TIER_LIMITS dict || Enterprise tier daily limit | $500,000 | Finance team, reviewed quarterly | TIER_LIMITS dict || Unknown tier handling | Defaults to "free" (most restrictive) | Safety decision, Jan 2023 | Fallback logic || Upgrade grace period | 24 hours | Avoids blocking during tier propagation delay | UPGRADE_GRACE_HOURS |
## Historical Context
- Tier limits introduced after Dec 2022 billing incident. A compromised account ran up $2.3M in charges overnight with no spending cap.- Unknown tier defaults to free rather than raising an error. This was a safety decision from Jan 2023 to prevent billing failures from becoming a security vulnerability.- 24h grace period exists because auth service updates tier immediately but billing cache takes up to 24h to propagate.
## Integration Dependencies
- **Ledger Aggregation Service**: Provides daily and monthly spend totals. Daily spend cached 60s. Monthly spend cached 5min.
## Risk Areas
- Grace period logic has a bug: _resolve_effective_tier returns user_tier in both branches of the if/else. The grace period code exists but has no practical effect. The original author may have intended to store and return the previous tier, but that data is not available in the function.Notification Router module:
# Notification Router: Extracted Knowledge
## Business Rules
| Rule | Value | Rationale | Source ||------|-------|-----------|--------|| Ops alert threshold | $10,000 | SOC2 audit Q2 2023, risk team requires immediate visibility | OPS_ALERT_THRESHOLD || SMS minimum amount | $100 | Cost reduction, Aug 2023 Twilio bill spike | SMS_MINIMUM_AMOUNT || Rate limit | 3 notifications/user/hour | Customer complaint, ticket INC-4521 | RATE_LIMIT_PER_HOUR || Email on all payments | Always | Compliance requirement | Hardcoded logic || Ops on all failures | Always regardless of amount | Safety decision | Hardcoded logic |
## Decision History
- Ops alert at $10k: Required by SOC2 audit, Q2 2023. Risk team needs immediate visibility into high-value transactions.- SMS disabled under $100: Product decision from Aug 2023. Twilio costs spiked because every microtransaction triggered an SMS.- Rate limit of 3/hour: Added in response to customer complaint INC-4521 about notification spam. Ops channel is exempt from rate limit.
## Integration Dependencies
- **Redis**: Stores notification counts with TTL keys for rate limiting.- **Email service**: Implicit (channel routing only, not called directly).- **Twilio/SMS**: Implicit (channel routing only).- **Slack Ops channel**: Implicit (channel routing only).
## Architectural Decisions
- Rate limiting drops user-facing notifications but never ops notifications. This means a user might not know their payment failed if they are over the rate limit, but the ops team will always know.- Channel selection is determined at routing time, not at send time. If preferences change between routing and sending, stale preferences apply.System-level summary:
# System Summary: Payment Service
## Module Interaction Map
payment_processor.py -> calls fraud scoring service (pre-charge validation) -> calls payment gateway (charge execution) -> calls financial ledger (post-charge recording)
user_limits.py -> calls ledger aggregation service (spend totals) -> consumed by payment_processor (pre-charge check, not shown in code)
notification_router.py -> queries Redis (rate limit state) -> consumed by payment_processor (post-charge notification, not shown in code)
## Cross-Cutting Concerns
- No shared error handling strategy. Each module handles (or ignores) failures differently.- No distributed tracing. If a transaction fails, correlating across the three modules requires manual log searching.- Ledger is a critical dependency for both payment_processor (writes) and user_limits (reads). Ledger outage affects both charge execution and limit enforcement.
## Concentrated Risk
- payment_processor.py: Highest risk. Contains payment flow, retry logic, and ledger write with no error handling. One person understood the full flow including the gateway incident history.- user_limits.py: Contains a latent bug in grace period logic that the original author likely did not intend.Compare that to reading the raw code. A new team member going through this documentation can understand the system in minutes. They know the why behind every decision. They know where the risks are. They even found a bug that nobody noticed because nobody else was reading this code carefully.
Making It Repeatable
The transformation is published. Now anyone on the team can run it:
atx custom run --name "tribal-knowledge-extraction" --path ./user-serviceatx custom run --name "tribal-knowledge-extraction" --path ./notification-serviceatx custom run --name "tribal-knowledge-extraction" --path ./billing-serviceOne transformation definition. Every repo in the org. The knowledge extraction is now a repeatable process, not a one-time event.
Before vs After
Before: You ask "why does the payment service retry three times?" in Slack. Nobody online knows. The person who added it left six months ago. You grep the git blame, find a commit from 2023 with the message "fix gateway issues," and guess.
After: You open the generated docs. The answer is right there with full context. The gateway had instability issues in Q3 2023. The retry was added as defense in depth. The gateway team fixed their side but the team kept the retry as a precaution. Took you 30 seconds instead of 30 minutes.
Before: A new hire joins and spends three months building context. They learn by breaking things, asking questions in Slack, and reading code with no roadmap.
After: Day one, they read the generated docs. They know which modules are high risk. They know which business rules came from compliance vs product decisions vs incident response. They know where the integration boundaries are. They can contribute meaningfully in the first week.
The important part: this is not a one time export. Run the transformation again after code changes. The docs evolve with the code. That is what makes them living docs instead of stale wiki pages.
Taking It Further: Make It Agentic
The playbook above is manual. You run the commands when you think about it. But ATX integrates into CI/CD pipelines. You can make documentation generation fully autonomous.
Option 1: Run on Every PR Merge
Add the transformation to your pipeline so docs regenerate after every significant code change. The documentation never drifts from reality.
# Example: GitHub Actions step- name: Regenerate knowledge docs run: | atx custom run --name "tribal-knowledge-extraction" --path . git add docs/ git commit -m "docs: regenerate knowledge extraction" git pushOption 2: Scheduled Weekly Runs
If continuous feels too heavy, run it on a schedule. Every Monday morning your team gets fresh documentation reflecting the past week's changes.
Option 3: Batch Across the Org
ATX supports batch execution across hundreds of repos using AWS Batch with Fargate. You can set up a campaign that runs your tribal knowledge extraction transformation across every service your team owns. The default configuration supports up to 128 concurrent jobs.
There is an open source sample repo from AWS that gives you production ready infrastructure for this. It includes scripts for orchestration, repository queuing, and status tracking across your portfolio.
Option 4: Combine with Other Transformations
Stack tribal knowledge extraction with ATX's built in code analysis to get documentation plus a tech debt report in one pass. Or run it alongside a version upgrade transformation so you get docs generated for the new code immediately after migration.
The CLI was designed to be embedded. Once you have a transformation that works, scaling it is a configuration problem, not a development problem.
What Else Can You Extract?
The transformation definition above focuses on business rules and architecture decisions. But you can define transformations for other knowledge extraction patterns:
API contract documentation: Extract all HTTP endpoints, request/response shapes, authentication requirements, and rate limits from the code. Generate an OpenAPI spec without writing one by hand.
Incident response runbooks: Find all error handling paths, retry strategies, circuit breakers, and fallback behaviors. Generate runbooks that explain what happens when each external dependency fails.
Onboarding guides: Identify module boundaries, entry points, and common code paths. Generate a "start here" guide that shows new engineers the critical path through the system.
Compliance mapping: Extract all validation rules, access controls, and audit logging. Map them to compliance requirements (SOC2, PCI, HIPAA) to show coverage.
Each of these is a separate transformation definition. Define it once, publish it, run it on every repo. Your documentation strategy becomes a set of transformations that run automatically.
Tips
- Start with your highest risk repo. The one where only one person knows what is going on. That is your bus factor one service. Extract it first.
- Be specific in your transformation definition about what you want extracted. "Generate documentation" is too vague. "Extract business rules, their threshold values, and the historical context for why those values were chosen" gives ATX something concrete to work with.
- Use the output as a starting point. Have team members read the generated docs and annotate anything the tool missed or got wrong. Then feed those corrections back into the transformation definition to improve future runs.
- Run it before the person leaves, not after. If the expert is still around, they can validate the output and fill gaps. The generated docs become the agenda for your knowledge transfer sessions instead of starting from a blank page.
- Treat transformation definitions like code. Version them, review them, improve them over time. A good extraction transformation gets better as you refine what to look for.
Get Started
Install the ATX CLI and point it at your riskiest codebase. The one where only one person holds all the context. Generate the documentation today. Not after they give notice.
# Install ATX CLIpip install aws-transform
# Start interactive modeatx
# Or run an existing transformation directlyatx custom run --name "tribal-knowledge-extraction" --path ./your-risky-serviceThe knowledge was always in the code. ATX just makes it readable.
Resources:
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article