TL;DR
Amazon Bedrock AgentCore 에이전트는 LLM과 도구 응답을 기다리는 동안에도 호출자와 별도의 실행 특성을 가지므로, 응답을 기다리는 Lambda를 계속 유지하면 에이전트 추론 시간만큼 유휴 컴퓨팅 비용이 쌓입니다. 이 글은 동일한 문서 검증 파이프라인에서 동기 호출 안티패턴과 Task-token Callback, 직접 서비스 통합, Lambda Durable Function을 비교하며, 호출자가 요청만 전달하고 대기 구간을 해제하는 구조를 권장합니다. 한 테스트에서는 Step Functions 상태가 19.6초 활성화된 동안 Dispatcher Lambda 과금 시간은 4.8초였고, 직접 통합은 Lambda를 호출 경로에서 완전히 제거했습니다. 운영 시에는 timeout과 heartbeat, 안정적인 sessionId, AWS X-Ray 추적을 함께 적용해야 하며 AgentCore와 모델 비용은 네 방식에서 동일합니다.
섹션별 상세
# The tool the agent calls once it reaches a verdict
@tool
def conclude_validation(approved: bool, issues: list, summary: str) -> str:
verdict = {"approved": approved, "issues": issues, "summary": summary, "source": "agentcore"}
# A Step Functions task token was passed: resume that execution
if task_token:
sfn.send_task_success(taskToken=task_token, output=json.dumps(verdict))
return "Step Functions resumed."
# A durable-function callback ID was passed: resume the durable function
if callback_id:
lambda_client.send_durable_execution_callback_success(
CallbackId=callback_id, Result=json.dumps(verdict).encode("utf-8"))
return "Durable function resumed."
# Neither was passed: this is a synchronous call, return the verdict inline
return "Verdict recorded."에이전트가 판정을 마친 뒤 task token이나 durable-function callback ID가 있으면 해당 실행을 재개하고, 둘 다 없으면 판정을 동기 응답으로 반환합니다.
@app.async_task
async def validate_document_async(prompt, document, extracted_text):
# Background work; conclude_validation fires the right callback when done
agent = build_agent()
await agent.invoke_async(message(prompt, document, extracted_text))
@app.entrypoint
async def handler(event):
task_token = event.get("taskToken") # passed by the task-token pattern callback
callback_id = event.get("callbackId") # passed by the durable-function pattern
# Asynchronous: start the work and return "accepted" right away
if task_token or callback_id:
asyncio.create_task(validate_document_async(...))
return {"status": "accepted"}
# Synchronous: run now and return the verdict in the response
agent = build_agent()
await agent.invoke_async(message(...))
return verdict호출 이벤트에 task token이나 callback ID가 있으면 에이전트 작업을 백그라운드에서 시작하고 즉시 accepted를 반환하며, 신호가 없으면 동기 실행으로 판정을 반환합니다.
// Start the agent, pass the task token, and return without waiting
const response = await agentcore.send(
new InvokeAgentRuntimeCommand({
agentRuntimeArn: AGENT_RUNTIME_ARN,
payload: new TextEncoder().encode(JSON.stringify({ ...payload, taskToken })),
runtimeSessionId: sessionId,
})
);
// Returning here does not complete the step. Step Functions stays paused until
// the agent calls SendTaskSuccess with this task token.
return { dispatched: true };Lambda가 AgentCore 호출에 task token을 포함해 요청을 전달한 뒤 즉시 종료하고, Step Functions는 에이전트의 SendTaskSuccess 호출까지 일시 중지됩니다.
- 동기 호출에서 Lambda의 과금 시간은 에이전트의 처리 시간과 거의 같아지지만, 비동기 task-token 방식에서는 호출 함수가 요청을 전달한 뒤 종료된다. — 동기 호출 안티패턴 설명과 Pattern 1 비용 설명
- 직접 서비스 통합은 Lambda 없이 Step Functions가 bedrockagentcore:invokeAgentRuntime을 호출하도록 구성한다. — Pattern 2의 ValidateDirect 상태 정의와 Cost 단락
// Suspend the function until the agent calls back
const result = await ctx.waitForCallback(
"validate-agentcore",
async (callbackId) => dispatchAgentCore(callbackId, document, extractedText, executionId),
{ timeout: { seconds: 120 } }
);Lambda Durable Function이 AgentCore 요청을 발송한 뒤 callback이 도착할 때까지 실행을 중단하고, 최대 120초 후 timeout을 적용합니다.
- Lambda Durable Function은 context.waitForCallback으로 실행을 중단하고 SendDurableExecutionCallbackSuccess로 재개한다. — Pattern 3 코드와 비용 설명
용어 해설
- Task-token Callback
- — AWS Step Functions가 작업을 일시 중지한 뒤 task token을 외부 작업에 전달하고, 작업 완료 시 해당 token으로 실행을 재개하는 비동기 호출 방식입니다. 호출 Lambda는 요청만 전달하고 종료하므로 에이전트 처리 시간 동안 유휴 컴퓨팅 비용이 발생하지 않습니다.
- 직접 서비스 통합(Direct Service Integration)
- — Step Functions가 중간 Lambda 없이 AWS SDK 서비스 통합을 통해 Amazon Bedrock AgentCore를 직접 호출하는 방식입니다. 에이전트 결과가 다음 상태로 바로 전달되며, 호출자 Lambda가 기다리며 실행되는 구간을 제거합니다.
- 내구성 함수(Durable Function)
- — Lambda Durable Execution SDK를 사용해 함수 실행을 중단했다가 callback으로 재개하는 오케스트레이션 방식입니다. 함수는 에이전트 응답을 기다리는 동안 컴퓨팅 비용을 발생시키지 않고, 중단 전후의 짧은 실행 구간만 과금됩니다.
- Model Context Protocol
- — AI 에이전트가 외부 도구나 서비스와 통신할 때 사용하는 프로토콜입니다. Amazon Bedrock AgentCore가 MCP 호출 결과를 기다리는 동안에는 AgentCore 런타임의 CPU가 과금되지 않고 메모리만 과금된다는 맥락에서 등장합니다.
- AWS X-Ray
- — 분산 애플리케이션의 실행 구간과 지연을 추적하는 AWS 서비스입니다. 이 글에서는 Step Functions와 Lambda에 추적을 활성화해 에이전트가 추론한 시간과 호출자가 실제로 대기한 시간을 구분하는 용도로 사용합니다.
기술
- Amazon Bedrock AgentCore
- AWS Lambda
- AWS Step Functions
- Amazon Elastic Compute Cloud
- Model Context Protocol
- Amazon Bedrock Guardrails
- AWS X-Ray
- @aws/durable-execution-sdk-js
- Amazon Bedrock model inference
활용 사례
- 부동산 금융 문서의 OCR 및 계약서 검증
- 에이전트 판정에 따른 대출 승인 또는 수정 요청
- 느린 AI 에이전트를 포함한 서버리스 파이프라인
- 사용자 정의 전처리와 후처리가 필요한 비동기 워크플로
- 상태 머신 또는 코드 기반으로 구성하는 복잡한 비동기 업무
AI 요약 · 북마크 · 개인 피드 설정 — 무료
출처 · 인용 안내
인용 시 "요약 출처: AI Trends (aitrends.kr)"를 표기하고, 사실 확인은 원문 보기 기준으로 진행해 주세요. 자세한 기준은 운영 정책을 참고해 주세요.