Build intelligent security for healthcare APIs with Amazon Bedrock

If you manage Fast Healthcare Interoperability Resources (FHIR) APIs, you must balance open patient data access with strict data protection requirements. Static security rules require constant updates as clinical workflows evolve, and maintaining them manually creates compliance gaps. With Amazon Bedrock, a fully managed service that provides access to foundation models (FMs) through a single API, you can build intelligent security for your healthcare APIs. This security monitors access patterns, classifies data sensitivity automatically, and generates compliance reports in natural language. This approach can help reduce documentation effort, reduce manual rule maintenance, and adapt your security monitoring as clinical workflows change.

In this post, you learn how to add context-aware security monitoring to FHIR APIs using Amazon Bedrock. First, we explain the architecture that separates security monitoring from the FHIR API request path, so you can add behavioral analysis without affecting API latency. Then we walk through implementing anomaly detection with Amazon Bedrock and Structured Outputs, with the ability to catch access patterns that static rules miss. Next, we demonstrate automated data sensitivity classification, which removes the need for hardcoded mapping tables. Finally, we show how to generate compliance reports in natural language, reducing audit preparation time. The solution uses AWS Lambda, Amazon API Gateway, AWS HealthLake, Amazon EventBridge, Amazon Cognito, Amazon Bedrock Guardrails, and Amazon Comprehend Medical. It includes an accompanying code sample with a complete AWS CloudFormation template, five AWS Lambda functions, and deployment scripts you can adapt for your environment.

Prerequisites

To deploy this solution, you need:

  • An active AWS account with administrative access.
  • AWS Command Line Interface (AWS CLI) v2 installed and configured (aws configure).
  • Amazon Bedrock now grants access to supported models automatically. Verify that the models are available in your AWS Region by checking the Amazon Bedrock model access page.
  • A verified email address for Amazon Simple Notification Service (Amazon SNS) security alert notifications.
  • If your AWS account has never used Amazon API Gateway with Amazon CloudWatch Logs integration, you must first set a CloudWatch Logs role ARN in your account’s API Gateway settings. Without this, the deployment fails with “CloudWatch Logs role ARN must be set in account settings.” See Set up CloudWatch API logging in API Gateway for instructions.
  • Estimated deployment time: 10-15 minutes. Estimated monthly cost varies based on usage. See the Amazon Bedrock pricing page for current rates. AWS HealthLake charges are separate.

Overview of the architecture

You get visibility into who accesses FHIR data and whether that access looks normal. The foundation models in Amazon Bedrock evaluate each request against the user’s historical behavior, role, and the sensitivity of the requested data. The result is a risk assessment in plain English that you can act on.

Your existing authorization controls stay in place. You continue to enforce role-based access control (RBAC) and validate JSON Web Tokens (JWTs), the signed tokens that prove a user’s identity, through an AWS Lambda authorizer. On top of that, you gain behavioral analysis that catches patterns a static rule cannot. For example, a user accessing data within their permissions but at an unusual volume or time of day triggers an alert.

The following diagram shows how security monitoring runs separately from the main API path, so it doesn’t add latency to clinical workflows.

Architecture diagram showing FHIR API requests flowing through Amazon API Gateway and a Lambda authorizer, with asynchronous security monitoring through Amazon EventBridge and Amazon Bedrock

Figure 1: Architecture of an Amazon Bedrock powered FHIR API security monitoring system

Here’s how the request-then-analyze flow works. Amazon API Gateway receives incoming FHIR requests and enforces throttling and request validation. An AWS Lambda authorizer validates the JWT and checks fine-grained permissions stored in Amazon DynamoDB.

AWS HealthLake then serves the FHIR data as a HIPAA-eligible, fully managed FHIR R4 data store. The FHIR processor AWS Lambda function captures access details and routes them through Amazon EventBridge to three asynchronous AWS Lambda functions: an anomaly analyzer, a sensitivity classifier, and a compliance reporter. Each function invokes Amazon Bedrock through an Amazon Bedrock Guardrails resource that anonymizes protected health information (PHI) in both prompts and responses. The anomaly analyzer additionally uses Amazon Comprehend Medical to redact PHI before writing to audit logs. Amazon CloudWatch captures structured logs throughout this flow for audit trails.

You benefit from fully asynchronous analysis. Amazon EventBridge routes the access event to the analyzer AWS Lambda function after the FHIR response has already returned to the client. Your API latency stays unaffected while you get continuous security monitoring.

If the analyzer is temporarily unavailable, the FHIR API continues serving requests normally. The monitoring layer doesn’t block clinical workflows.

HIPAA safeguards

The solution implements multiple layers of PHI protection to prevent protected health information from leaking through the monitoring pipeline:

  • Amazon Bedrock Guardrails – An AWS::Bedrock::Guardrail resource is deployed with the AWS CloudFormation template. It detects and anonymizes personally identifiable information (PII) entities (names, Social Security numbers, addresses, phone numbers, medical record numbers) in both prompts sent to Amazon Bedrock and model responses. SSNs and passport numbers are blocked entirely rather than anonymized.
  • Amazon Comprehend Medical – Before writing an Amazon Bedrock response to Amazon CloudWatch Logs, the anomaly analyzer passes the text through the DetectPHI API in Amazon Comprehend Medical. Detected PHI entities are replaced with type tags (for example, [NAME], [DATE]) so that audit logs remain useful for compliance review without containing actual patient data.
  • IP generalization – The anomaly analyzer prompt never sends raw IP addresses to Amazon Bedrock. Instead, it classifies the source as “internal” or “external” based on RFC 1918 ranges, preventing PII from entering the model context.
  • PHI-free alerts – When the anomaly analyzer triggers an Amazon SNS alert, the notification contains only a hashed reference ID and the risk level. The security team retrieves full details from the audit log using the reference ID, which helps prevent email notifications from containing PHI.
  • Structured Outputs – Amazon Bedrock calls in this solution use Structured Outputs with JSON schemas and enum-constrained fields (fields limited to a fixed set of valid values). This reduces free-text parsing and helps confirm that model responses conform to a predictable format, reducing the risk of unexpected PHI appearing in downstream processing.
  • Sanitized error messages – FHIR API error responses return generic messages to the client rather than internal exception details, which could inadvertently include patient data from AWS HealthLake responses.

Anomaly detection with Amazon Bedrock

You can detect sophisticated access anomalies that rule-based systems miss by analyzing behavioral patterns across diverse clinical user populations. The analyzer AWS Lambda function is the core of this architecture. Every API call generates an access event, and the foundation model evaluates that event against the user’s role, access history, and the nature of the request.

Consider a doctor who normally accesses 5-15 patient records during business hours. If that same doctor downloads 500 records at 3 AM, a static rule would need explicit thresholds for every role and time combination. With Amazon Bedrock, you evaluate the full context and get a risk assessment with a plain-English explanation.

Clinical user populations are diverse: physicians, nurses, billing staff, researchers, and third-party integrations. Each group has different normal access patterns, and those patterns shift over time. A researcher running a retrospective study might legitimately access thousands of records in a single session. The foundation model distinguishes that from unauthorized access by examining the user’s role, the nature of the request, and whether the access followed normal authentication patterns.

The anomaly detection builds per-user behavioral baselines rather than applying population-level thresholds. This approach reduces the risk of systematically flagging legitimate access patterns from night-shift clinicians, international researchers, or on-call physicians who routinely operate outside standard business hours.

Different caller types carry different risk profiles. SMART on FHIR applications, patient portals, and Health Information Exchange (HIE) connections each have distinct expected behaviors. The access event includes the OAuth client_id, so the analyzer can maintain app-specific baselines and apply differentiated risk scoring based on the integration type.

Organizations can further enrich access events with clinical context such as on-call schedules, emergency department activation status, or care team assignments. For example, a doctor accessing 500 records at 3 AM during a mass casualty event should not trigger the same risk assessment as the same pattern on a routine night. The prompt design accommodates this additional context when available.

This implementation uses a fail-open approach. Fail-open means that if the analyzer encounters an error, it logs the failure but doesn’t block the original API request. We chose this over a fail-closed approach (which would block requests on error) because an analyzer outage shouldn’t create availability issues for clinical workflows. The FHIR API continues serving requests normally while the monitoring layer recovers.

The anomaly analyzer uses the Amazon Bedrock Converse API with Structured Outputs to enforce a JSON schema with enum-constrained risk levels (LOW, MEDIUM, HIGH). An Amazon Bedrock Guardrails resource anonymizes PHI in prompts and responses, and Amazon Comprehend Medical redacts PHI before audit logging. For HIGH-risk events, Amazon SNS sends a PHI-free alert containing only a hashed reference ID. See anomaly_analyzer/handler.py in the accompanying code sample for the complete implementation.

Data sensitivity classification

FHIR resources vary in sensitivity. A mental health Observation carries more sensitivity than a routine blood pressure reading. Certain clinical data types, such as substance abuse treatment records, might require additional safeguards based on applicable regulations. Note that sensitivity classification informs access decisions but doesn’t replace consent management, which should be implemented according to your organization’s policies.

You can classify FHIR resources by sensitivity level without hardcoded mapping tables using Amazon Bedrock. When a resource is created or updated in AWS HealthLake, an Amazon EventBridge rule triggers a classification function. That function sends the resource metadata to Amazon Bedrock, which evaluates the resource type, clinical codes, and category. It then assigns a sensitivity level: PUBLIC, INTERNAL, CONFIDENTIAL, or RESTRICTED.

For example, Amazon Bedrock classifies an Observation with a Logical Observation Identifiers Names and Codes (LOINC) code for blood glucose (2345-7) as INTERNAL. It classifies an Observation with a code for HIV test results (7018-2) as RESTRICTED. The model makes this distinction based on the clinical meaning of the codes. When new code systems or resource categories appear, the classification adapts without code changes.

Amazon DynamoDB stores the classification alongside the resource ID. When a user requests that resource, the AWS Lambda authorizer checks whether the user’s clearance level matches the resource’s classification before granting access. This gives you a dynamic, content-aware authorization layer on top of the standard RBAC.

For classification tasks, you use Anthropic’s Claude Haiku 4.5 foundation model (FM) on Amazon Bedrock, which keeps latency low and costs minimal. For the more complex access pattern analysis where accuracy matters more than speed, you use Anthropic’s Claude Sonnet 4.5 FM on Amazon Bedrock. For an organization processing 100,000 FHIR API calls per month, expect Amazon Bedrock costs in the range of tens of dollars, depending on prompt length and model selection. For current per-token pricing, see the Amazon Bedrock pricing page. You can monitor usage and costs in the AWS Billing and Cost Management console.

The sensitivity classifier uses Structured Outputs with a fixed set of valid values (PUBLIC, INTERNAL, CONFIDENTIAL, RESTRICTED) to guarantee a valid classification. If classification fails, the function defaults to CONFIDENTIAL (fail-secure). See sensitivity_classifier/handler.py in the accompanying code sample.

Compliance reporting

Healthcare audits require documentation of who accessed what data, when, and why. Security teams typically spend days aggregating logs, cross-referencing user activity, and writing narrative summaries. You can transform raw access logs into readable compliance reports automatically using Amazon Bedrock.

A scheduled AWS Lambda function runs monthly using Amazon EventBridge Scheduler. It retrieves the access logs for the reporting period and sends them to Amazon Bedrock with instructions to generate a compliance summary. The output includes total request counts by resource type, unique user activity broken down by role, flagged access events and their resolutions, and recommendations for improving security posture.

The prompt instructs the foundation model to organize the report by security control category (administrative, physical, and technical). This structure helps security teams review findings systematically. Each flagged event includes the original risk assessment, the resolution status, and a timeline of actions taken.

This approach automates the manual steps of log aggregation, cross-referencing, and narrative writing, reducing the time compliance teams spend on each report.

The compliance reporter uses Structured Outputs with a schema that maps each section to a security control category. Reports are saved to Amazon Simple Storage Service (Amazon S3) with AWS Key Management Service (AWS KMS) encryption and archived to Amazon S3 Glacier after one year. See compliance_reporter/handler.py in the accompanying code sample.

Cleaning up

To avoid ongoing charges, delete the resources created by this solution when you are finished testing. Run the cleanup script from the accompanying code sample: ./src/scripts/cleanup.sh dev us-east-1. This removes the AWS CloudFormation-managed resources including the API Gateway REST API, all five AWS Lambda functions, both Amazon DynamoDB tables, the Amazon EventBridge event bus and rules, the Amazon Cognito user pool, the Amazon SNS topic, the Amazon S3 compliance reports bucket, and the Amazon CloudWatch log groups. If you created an AWS HealthLake datastore separately for end-to-end testing, delete it manually. AWS HealthLake charges approximately $0.694 per hour (~$500/month) while active.

Conclusion

You now have a proof-of-concept security monitoring pattern that adapts to your environment as access patterns change. In this post, you learned how to detect anomalous access patterns, classify data sensitivity levels automatically, and generate security audit reports in natural language using Amazon Bedrock foundation models.

If you’re evaluating this approach, start by reviewing the architecture diagram and code sample in this post. Explore the Amazon Bedrock User Guide to understand foundation model capabilities, and review the AWS HealthLake User Guide to assess how FHIR R4 data management fits your environment.

If you’re ready to deploy, follow these steps:

  • Run aws configure to set your AWS credentials and target AWS Region (for example, us-east-1). Verify that Anthropic’s Claude Sonnet 4.5 and Anthropic’s Claude Haiku 4.5 are available in your target Region.
  • Run the deployment script: ./src/scripts/deploy.sh your-email@example.com dev us-east-1. This packages the Lambda code, uploads it to Amazon S3, and deploys the AWS CloudFormation stack with the required infrastructure (Amazon API Gateway, AWS Lambda functions, Amazon DynamoDB tables, Amazon EventBridge rules, Amazon Cognito, Amazon SNS, Amazon S3, and the Amazon Bedrock Guardrails resource). Check your email and confirm the Amazon SNS subscription.
  • Customize the prompts in the anomaly analyzer and sensitivity classifier AWS Lambda functions to match the organization’s risk tolerance, clinical roles, and data sensitivity definitions.
  • (Optional) Create an AWS HealthLake datastore for end-to-end testing. Note that AWS HealthLake charges approximately $0.694 per hour, so create it only when actively testing and delete it promptly. Then send test events through Amazon EventBridge and verify the end-to-end flow by checking Amazon CloudWatch Logs for each Lambda function.

After deployment, test the anomaly detection by sending FHIR API requests with varying patterns:

  • Simulate an unusual access pattern by requesting a high volume of records outside normal hours. Send a GET request to your API Gateway endpoint for 500 Patient resources using a valid JWT token. The anomaly analyzer should flag this as MEDIUM or HIGH risk.
  • Simulate a normal access pattern by requesting a small number of records during business hours. The analyzer should assign a LOW risk level.
  • Simulate a cross-role access attempt where a billing user requests clinical data such as laboratory Observations. This tests whether the model identifies role-resource mismatches.

After each test, check the Amazon CloudWatch Logs for the anomaly analyzer Lambda function and verify that Amazon SNS delivered alerts for HIGH-risk events. The README in the accompanying code sample includes the specific API endpoints and curl commands for each test scenario.

If you already run FHIR APIs in production, you can integrate this monitoring layer alongside existing Amazon API Gateway and AWS Lambda authorizers without modifying the request path. Add the asynchronous Amazon EventBridge-to-Bedrock flow as a parallel monitoring channel and tune the prompts to reflect the organization’s specific role definitions and risk profiles.

To extend the solution further, consider integrating the Amazon SNS alerts with existing security information and event management (SIEM) tools for centralized monitoring. You can also add prompt templates for common healthcare scenarios such as research data access reviews, emergency break-the-glass overrides, and bulk data export risk assessments. You can also tune the prompts to reflect organization-specific risk profiles, or scale the architecture for high-volume environments by adjusting the AWS Lambda concurrency settings and Amazon DynamoDB throughput.

For deeper guidance, see the Amazon Bedrock User Guide, the AWS HealthLake User Guide, the Amazon API Gateway Developer Guide, and the Amazon CloudWatch User Guide.

Share your experiences and questions in the comments. Contact an AWS Representative to discuss your healthcare security implementation.

Further reading


About the authors

Durgesh Nath

Durgesh Nath

Durgesh is a Senior Technical Account Manager at AWS and an AWS Golden Jacket recipient – one of the highest honors in the AWS partner and technical community. With over 19 years of experience building and scaling technology across diverse domains, he works across cloud strategy, security, and Generative AI. With deep expertise in cloud security and a growing focus on AI-driven innovation, Durgesh brings both the technical depth and strategic perspective that enterprise customers rely on to accelerate their AWS journey.

Derrick Swamy

Derrick Swamy

Derrick is a Senior Solutions Architect at AWS, supporting Healthcare segment customers with a focus on Security and Generative AI services. With a background spanning both Professional Services and Solutions Architecture, Derrick brings deep technical expertise and a passion for solving complex problems at the intersection of cloud, security, and AI. He actively supports the Security community and is at the forefront of exploring new frontiers with generative AI technology.