Sentry's Span Hierarchy Exposed a Silent Retry in My 5-Agent Pipeline. One Agent Took 22.6s, the Others Took 5. A developer built an AWS Security Posture Agent using five specialist AI agents on CrewAI with Amazon Bedrock Nova Pro. One agent took 22.6 seconds while others averaged 5-10 seconds; Sentry's trace waterfall revealed the SecurityScanner agent was overwhelmed by a 27KB JSON payload from the IAMAnalyzer tool, causing CrewAI's retry logic to fire. The fix limited IAM role analysis to the top 20 most active roles, reducing the payload and normalizing execution times. This is a submission for DEV's Summer Bug Smash: Clear the Lineup powered by Sentry. I built an AWS Security Posture Agent : five specialist AI agents that scan your AWS account for security misconfigurations, map findings to CIS benchmarks, score risk, and generate copy-paste fix commands. The agents run sequentially on CrewAI with Amazon Bedrock Nova Pro as the LLM: 1. ResourceDiscovery → inventories EC2, S3, Lambda, IAM, SGs, API GW, DynamoDB 2. SecurityScanner → finds open ports, public buckets, admin roles, insecure configs 3. ComplianceChecker → maps to CIS AWS Foundations Benchmark 4. RiskScorer → severity × blast radius × exploitability 5. RemediationPlanner → generates AWS CLI fix commands Each agent has custom boto3 tools that make real AWS API calls against a live account with 90 IAM roles, 14 S3 buckets, 9 security groups, and 7 Lambda functions. Not test data. Real findings. Five AI agents scan your AWS account. Find misconfigurations. Score risk. Get fix commands. Most AWS accounts accumulate security debt silently. Open SSH ports from testing. S3 buckets without encryption. IAM roles with full admin access that nobody remembers creating. Manual audits miss things. AWS Config rules cost money. SecurityHub is noisy. This agent scans your account in 60 seconds, finds real issues, maps them to CIS benchmarks, scores risk, and gives you the exact AWS CLI command to fix each one. On a real AWS account 90 IAM roles, 14 S3 buckets, 9 security groups, 7 Lambda functions : 97 security findings ├── CRITICAL: open SSH/RDP from 0.0.0.0/0, IAM users without MFA ├── HIGH: admin roles, unencrypted EBS, missing public access blocks ├── MEDIUM: deprecated Lambda runtimes, missing versioning, stale SGs └── …Here's the full scan running against my AWS account. The scan portion is sped up 4x, results walkthrough is at normal speed: My first instinct was to blame Bedrock latency. Every time something is slow you blame the LLM, right? The SecurityScanner agent was taking 22.6 seconds while every other agent averaged 5-10 seconds. Without visibility into what was happening inside each agent's execution, I would have added time.time calls and guessed. Sentry's trace waterfall told a different story. The real problem wasn't Python execution time or network latency. It was the LLM getting a context payload it couldn't process cleanly on the first attempt. The root cause: my IAMAnalyzer tool was fetching all 90 IAM roles from the account 59 after filtering service-linked roles , serializing them into a 27KB JSON blob, and handing that entire payload to the LLM as tool output. The context window got overwhelmed. CrewAI's internal retry logic kicked in, burning tokens on a second attempt with even more context. One tool. Wrong default. The entire pipeline suffered. PR with the fix: The IAMAnalyzer tool was fetching every single role in the account 90 of them, 59 after filtering service-linked ones and dumping the full details into a single JSON blob. That blob hit 26,980 characters. The LLM choked on it, CrewAI retried the task, and the SecurityScanner agent ended up taking 22.6s while every other agent finished in 5-10s. Added Sentry spans to each agent and tool. The trace waterfall made it obvious: SecurityScanner was twice as wide as everything else. Drilled into the tool spans and saw result length chars: 26980 on iam analyzer vs ~4000 on the other tools. 7x output disproportion. That was the problem. Three things in iam analyzer.py : RoleLastUsed date, only analyze the top 20 most active ones. The rest are stale roles nobody has touched in months.The core change lives in src/security posture/tools/iam analyzer.py . Here's the before and after: Before the bug : Fetches ALL roles without pagination limit roles = iam.list roles MaxItems=100 role details = for role in roles "Roles" : role name = role "RoleName" if role.get "Path", "" .startswith "/aws-service-role/" : continue Analyzes every single role... attached = iam.list attached role policies RoleName=role name ...builds massive JSON output This produces 26,980 characters of JSON for an account with 90 roles. The LLM chokes on it. After the fix : FIX: Paginate and sort by relevance all roles = paginator = iam.get paginator "list roles" for page in paginator.paginate : all roles.extend page "Roles" Filter service-linked roles 31 roles, can't modify anyway auditable roles = r for r in all roles if not r.get "Path", "" .startswith "/aws-service-role/" Sort by last used date most active first auditable roles.sort key= last used sort key, reverse=True Take only top 20 roles roles to analyze = auditable roles :max roles Plus a token budget guard at the end: Token budget guard: truncate if output exceeds threshold if len output 4000: result "role summary" = {"role name": r "role name" , "policies": r.get "attached policies", } for r in role details result "note" = "Role details truncated to stay within token budget" output = json.dumps result, indent=2, default=str Three changes. Pagination, relevance sorting, and a safety valve. The SecurityScanner stopped retrying. Results first: | Metric | Before | After | Improvement | |---|---|---|---| | IAM tool output | 26,980 chars | 15,532 chars | 42% smaller | | SecurityScanner time | 22.6s | 17.8s | 21% faster | | IAM API calls | 59 | 20 | 66% fewer | | Total pipeline | 62.0s | 57.7s | 7% faster | | Security findings | 97 | 97 | No coverage loss | The 21% improvement on the SecurityScanner came from the LLM completing analysis in a single pass instead of retrying. How I found it: The fix itself is simple. The interesting part is how Sentry pointed me straight to it. Without the trace waterfall, all I would have seen is "pipeline takes 62 seconds." The trace said otherwise: gen ai.invoke agent span gen ai.execute tool span iam analyzer tool span showed a result length chars of 26,980 security group analyzer at 4,200 chars and s3 config checker at 3,800 charsThe disproportion was the clue. If the tool output is 7x larger than its siblings, reduce it. I used Sentry's AI Agent Monitoring to instrument a multi-agent CrewAI pipeline from scratch. This isn't a web app or API. It's five autonomous AI agents making LLM calls and executing custom tools. Standard APM wouldn't help here. Every pipeline run creates a Sentry transaction with this span hierarchy: Transaction: "Security Posture Scan" 57s ├── gen ai.invoke agent: ResourceDiscovery │ └── gen ai.execute tool: aws resource scanner ├── gen ai.invoke agent: SecurityScanner │ ├── gen ai.execute tool: security group analyzer │ ├── gen ai.execute tool: s3 config checker │ ├── gen ai.execute tool: iam analyzer │ ├── gen ai.execute tool: ec2 security checker │ └── gen ai.execute tool: lambda security checker ├── gen ai.invoke agent: ComplianceChecker ├── gen ai.invoke agent: RiskScorer └── gen ai.invoke agent: RemediationPlanner For each agent in main.py : with start span op="gen ai.invoke agent", name=f"invoke agent {agent name}", as agent span: agent span.set data "gen ai.operation.name", "invoke agent" agent span.set data "gen ai.agent.name", agent name agent span.set data "gen ai.request.model", "amazon.nova-pro-v1:0" agent span.set data "gen ai.pipeline.name", "security-posture-scan" task output = task obj.execute sync agent=task obj.agent, context=context, tools=task obj.agent.tools, agent span.set data "duration seconds", round elapsed, 2 agent span.set data "output length chars", len str task output For each tool decorator in monitoring.py : python def trace tool tool name: str : def decorator func : @functools.wraps func def wrapper args, kwargs : with start span op="gen ai.execute tool", name=f"execute tool {tool name}", as span: span.set data "gen ai.tool.name", tool name result = func args, kwargs span.set data "result length chars", len result try: data = json.loads result if "findings count" in data: span.set data "findings count", data "findings count" except json.JSONDecodeError, KeyError : pass return result return wrapper return decorator The trace waterfall made the bottleneck visually obvious. The SecurityScanner span was nearly twice the width of any other agent, 22.6 seconds while others averaged 5-10s. Inside it, the iam analyzer tool span showed result length chars: 26980 while s3 config checker showed 3,800 and security group analyzer showed 4,200. The granularity goes down to individual boto3 calls. Every GetPublicAccessBlock , ListRoles , and ListAttachedRolePolicies shows up as its own span. Before the fix SecurityScanner dominates the trace at 22.6s : After the fix all agents proportional, no single bottleneck : The iam analyzer output dropped from 26,980 chars to 15,532, and the SecurityScanner stopped triggering retry logic. | Feature | How I Used It | |---|---| Distributed Tracing | Full pipeline trace from start to final report | AI Agent Monitoring | gen ai.invoke agent spans for all 5 agents | Tool Execution Tracing | gen ai.execute tool spans for all 5 boto3 tools | Custom Span Data | Token counts, output sizes, duration, finding counts | Error Monitoring | Exception capture with sentry sdk.capture exception | Breadcrumbs | Agent completion events via task callbacks | Transaction Metadata | Model name, pipeline config, agent count | Standard logging tells you an agent "finished." It doesn't tell you which tool inside which agent returned a 27KB payload that triggered a retry you never asked for. With five agents each making their own LLM calls and tool executions, you need span-level visibility. Sentry's gen ai.invoke agent and gen ai.execute tool conventions gave me exactly that. I could see the problem in the trace waterfall before I even looked at the code. That's the difference between "add some logging" and actual AI observability. If you're running multi-agent pipelines, what's your observability setup? Curious if anyone else has hit similar tool-output-size problems with CrewAI or LangGraph. The agent found 97 real security findings in my AWS account. The fix is in production.