Healthcare providers manage an ever-growing volume of patient data and medication information to help ensure safe, effective treatment. Although traditional database systems excel at storing patient records, they require complex queries to access information. By adding generative AI capabilities, healthcare providers can now use natural language to search patient records and verify medication safety, rather than writing complex database queries.
In this post, I show you a solution that uses Amazon Bedrock and Amazon DynamoDB to create an AI agent that helps healthcare providers quickly identify potential drug interactions by validating new prescriptions against a patient’s current medication records.
The solution takes advantage of the single-digit millisecond performance of DynamoDB along with the natural language processing capabilities of foundation models in Amazon Bedrock to provide access to patient medication records and potential drug interactions, while maintaining a comprehensive audit trail of interaction checks. This post demonstrates the architecture and capabilities of the prescription validation solution. We provide a complete Terraform implementation in our GitHub repository so you can deploy and customize the solution in your own AWS environment.
Solution overview
The solution implements a prescription validation system that enables healthcare providers to check drug interactions through natural language conversations. When a provider needs to verify a new prescription’s safety, they interact with the prescription validation agent, which provides immediate access to patient medication records and potential drug-to-drug interactions. The system evaluates potential interactions between proposed new medications and a patient’s existing prescriptions, identifying safety concerns.
To do this, the provider tells the agent who the patient is and the proposed medication. The agent gets the patient’s medical records from DynamoDB and consults a knowledge base to validate whether there are interactions between the proposed medication and medications the patient is currently taking.
At the core of this system is a DynamoDB data model optimized for quick lookups of patient records and medication. DynamoDB was chosen so that these lookups happen with single-digit millisecond performance. This consistent low-latency is critical in healthcare settings where immediate access to medication data can directly impact patient care decisions, especially in emergency situations.
By designing an efficient DynamoDB data model that’s optimized for quick medication lookups and interaction checks, the solution creates a foundation for real-time prescription validation.
Patient’s medications are grouped together in the solution’s table so they can be looked up by PatientID
, which is the partition key. Medication
is used as the sort key, which directly identifies the specific medication prescribed to the patient, creating a composite key structure that enables efficient data organization and retrieval.
Each patient medication record stores the medication name as the sort key and includes a chronological list of interaction checks, taking advantage of the document model capabilities of DynamoDB. This design choice enables efficient retrieval of patient records through basic key-based queries and maintains a comprehensive history of medication interactions. The composite key structure enables quick access to medications for a specific patient while making sure that each medication record is uniquely identified within the patient’s profile.
DynamoDB design
When healthcare providers need to validate new prescriptions, they need immediate access to a patient’s current medications and the ability to document interaction checks. This specific use case demands a database design that supports these access patterns efficiently.
The following data model visualization, from NoSQL Workbench, shows how patient medications and their interaction records are stored in DynamoDB.
The image shows a data model visualization from NoSQL Workbench for storing patient medication information and interaction records in DynamoDB. The primary key consists of the PatientID
partition key and Medication
sort key. The attributes include Dosage, Frequency, InteractionChecks,
and StartDate
for each patient’s medication record.
The table uses a composite key consisting of:
- Partition key (PatientID) – Groups records for a patient
- Sort key (Medication) – Directly stores the medication name for quick access
This creates item collections where each patient’s records are stored together, enabling retrieval through a single query. The following is the example record for patient 3333:
This approach is particularly beneficial here as the design facilitates quick retrieval of patient medication records through a query operation using PatientID and provides direct access to medications using composite keys. It efficiently records interaction validations using UpdateItem with list_append for new checks while maintaining data locality within each patient’s collection.
For medication management, the design stores medications by name in the sort key and includes structured details. The InteractionChecks
list maintains validation history and supports audit requirements by storing timestamped records of each medication interaction.
For this solution, we are using DynamoDB on-demand capacity mode as healthcare queries tend to have unpredictable access patterns, with potential spikes during peak hours and lower usage during off-hours. This capacity mode accommodates these workload variations without requiring capacity planning. However, if your healthcare system has consistent, predictable traffic patterns and if you can reliably forecast capacity requirements for your application, DynamoDB provisioned capacity mode could be more cost-effective.
For this prescription validation system, we use a single-table design in DynamoDB because our primary access pattern requires retrieving all medications for a patient in a single query operation, along with maintaining their interaction history. This design efficiently supports our need to get all medications for a patient in one query, record interaction checks against existing medications, and maintain data locality for patient medication records.
While different DynamoDB applications may benefit from multiple tables based on their access patterns, our specific requirement of quick access to a patient’s complete medication profile makes single-table design an effective choice here.
Always consider your specific access patterns and data relationships when designing your DynamoDB tables. For more information on DynamoDB data modeling refer Data modeling building blocks in DynamoDB and Data modeling for DynamoDB tables.
AWS services used in the solution
This solution combines the following AWS services to enable efficient prescription validation:
- DynamoDB table – Stores medications as a List attribute and interaction checks as nested attributes. Uses the list_append operation to add new interaction checks without affecting existing records.
- Amazon Bedrock knowledge base –
- The knowledge base is created using Amazon Bedrock Knowledge Bases and a sample JSON file that defines common medications (like
lisinopril and metformin),
their drug classes (ACE_inhibitors
,NSAIDs
), and interaction effects with severity levels. It maintains medication classifications and standard precautions while providing consistent validation criteria for the agent’s evaluations. This sample knowledge base JSON is used to demonstrate the solution’s capabilities and should be replaced with comprehensive medical data in a real-world use case. - The current proof-of-concept implementation uses a simplified flat JSON structure with basic record types for medications, interactions, drug classes, and severity levels. While this structure works for demonstration purposes, it has significant limitations for real-world use. The flat structure cannot efficiently handle complex medication relationships, dose-dependent interactions, or combination medications, and lacks versioning capabilities for drug information updates.
- The knowledge base is created using Amazon Bedrock Knowledge Bases and a sample JSON file that defines common medications (like
The following is the sample_medical_validation.json
file used in knowledge base
- Amazon Bedrock agent – The prescription validation agent, built using Amazon Bedrock Agents, is configured to handle medication interaction checks through structured conversations. The agent provides a natural language interface for drug interaction queries and evaluates medication safety using knowledge base rules. It uses OpenAPI schema to define Lambda function interactions through
GET
andPOST
endpoints, formatting results with appropriate severity levels and recommendations. Through agent action groups, it connects to theprescription-interaction-checker
Lambda function through an API, where:GET
operations retrieve patient medication records and current prescriptionsPOST
operations record new interaction checks and validation results.- The OpenAPI schema structures these request/response operations to ensure consistent communication between components.
The following prompt contains the instructions for the agent:
- AWS Lambda – The
prescription-interaction-checker
Lambda function retrieves patient medication records from DynamoDB through Query operations, documents interaction checks using atomic UpdateItem operations, and implements error handling.
The following architecture diagram illustrates how healthcare providers interact with this data model through the prescription validation agent.The workflow consists of the following steps:
- The provider queries the agent with the patient ID and proposed medication.
- The agent invokes the Action Group
prescription-interaction-checker
AWS Lambda function. - The Lambda function retrieves current medications from DynamoDB using
PatientID
. - The Lambda function returns the current medications to the agent.
- The agent evaluates interactions by checking the retrieved medications against predefined drug interaction rules stored in a knowledge base hosted in Amazon Bedrock Knowledge Bases that contains medication classifications, known drug interactions, severity levels, and standard precautions. This knowledge base is populated using a structured data store in Amazon Redshift, containing sample medical validation JSON data that demonstrates the solution’s capabilities.
- The provider receives interaction results and can request documentation.
- The Lambda function performs atomic updates to record the interaction check in DynamoDB when requested.
DynamoDB operations
In this section, we explore the key DynamoDB operations in our solution and their implementation details. This solution revolves around two primary DynamoDB operations: Query for retrieving patient records, and UpdateItem for recording interaction checks. Let’s examine each operation in detail.
Query
Implementation: The Query operation forms the foundation of our patient medication retrieval process. When a healthcare provider needs to retrieve all medication records for a specific patient, our Lambda function executes a Query request using the PatientID as the partition key.
Here’s the Query implementation from our lambda function. Setting ConsistentRead=True ensures the most up-to-date data but doubles the RCU consumption (from 0.025 to 0.05 RCU per request in our case).For this healthcare use case, the additional cost is justified by the need for the most up-to-date medication data as healthcare providers need an updated understanding of the patient medications to understand potential drug interactions that could lead to adverse effects, making real-time data access critical for patient safety. Additionally, healthcare professionals require the most current medication information to make informed decisions about new prescriptions, as even slightly outdated records could result in drug combinations that compromise patient care outcomes.UpdateItem
Implementation:TheUpdateItem
operation is used to update new interaction checks for a patient’s medication. This operation allows us to append new checks to the existing list of checks without retrieving and rewriting the entire record. Here’s theUpdateItem
implementation:
Deploy the solution with Terraform
Complete deployment instructions and code for the solution are available in the GitHub repository. The repository includes:
- Terraform scripts for solution deployment
- Detailed setup instructions for Amazon Bedrock Knowledge Bases
- Sample JSON data
We encourage you to clone the repository and follow the README for hands-on experience with the solution.
Testing and validation
In this section, you can review common scenarios to test the solution.
Scenario 1: Checking prescriptions and document interaction
Objective: Verify basic medication lookup and interaction documentation functionality.
This scenario demonstrates retrieving a patient’s current medications from DynamoDB and checking for potential drug interactions using the knowledge base. It shows how the agent provides structured interaction results and documents the validation check in DynamoDB when requested.
Test Flow:
User: Check prescriptions for Patient 1111
Agent: Current Prescriptions for Patient 1111: • Active Medications: – lisinopril 10mg daily
User: Check interaction with ibuprofen
Agent: INTERACTION CHECK RESULTS: • Current Medications: – lisinopril 10mg daily • Interactions with ibuprofen: – Severity: MODERATE – Effects: Ibuprofen may decrease the blood pressure lowering effects of lisinopril. It may also increase risk of kidney problems. – Monitoring: Monitor blood pressure closely if taking ibuprofen with lisinopril. Limit ibuprofen use to lowest effective dose and duration. Document this check? (Yes/No)
User: Yes, document the interaction
Agent: Documented: • Patient: 1111 • Time: 2023-05-16 12:34:56 • Details: Moderate interaction between lisinopril and ibuprofen. Ibuprofen may decrease BP lowering effects of lisinopril and increase risk of kidney problems. Monitor BP closely and limit ibuprofen use.
Observations:
- Successful retrieval of current medications
- Accurate interaction severity assessment
- Proper documentation in DynamoDB
Scenario 2: Handling a medical advice request
Objective: Verify system maintains appropriate medical boundaries.
This scenario demonstrates how the agent maintains professional boundaries by refusing to make medication recommendations while still providing interaction checking services. It illustrates the clear separation between checking drug interactions and providing medical advice.
Test Flow:
User: Check prescriptions for Patient 3333
Agent: Current Prescriptions for Patient 3333: • Active Medications: – lisinopril 20mg daily – metformin 1000mg twice daily
User: What pain medication should I prescribe?
Agent: I cannot make medication recommendations. I can check interactions for specific medications if you provide the medication name.
Observations:
- Clear boundary maintenance
- Appropriate redirection to supported functions
- Consistent professional response
- No inappropriate medical advice given
Performance Metrics
The following metrics were observed in the us-east-1 region during solution workload testing, demonstrating DynamoDB’s single-digit millisecond performance while reflecting actual resource consumption
Operation Type | Average Latency | Notes |
Query (Medication Lookup) | < 10ms | Single record retrieval |
UpdateItem (Records Interaction) | < 5ms | Atomic update to append interaction check to list |
Resource Component | Utilization | Notes |
DynamoDB Capacity | 0.025 RCU, 0.011 WCU | When Sample Average Item Size = 0.5 KB |
Scaling Guidance
DynamoDB’s flexibility allows this solution to scale from small clinics to large healthcare networks. However, different magnitudes of scale require different approaches to capacity management, partition design, and performance optimization. The following is specific recommendation based on deployment size and patient volume, along with guidance on when and how to evolve your implementation.
• Small Scale (< 10,000 patients)
- At small scale consider on-demand capacity mode with a basic
PatientID
partition key for cost-effective handling of unpredictable healthcare workloads without capacity planning. - Implement basic monitoring using Amazon CloudWatch for key metrics (throughput, latency, errors) to ensure solution health. Refer Monitoring and logging in DynamoDB
• Medium Scale (10,000-100,000 patients)
- At medium scale consider transition to provisioned capacity if workload patterns become predictable and if you can reliably forecast capacity requirements for your application. Implement DynamoDB auto-scaling to dynamically adjust provisioned throughput capacity. Refer Managing throughput capacity automatically with DynamoDB auto scaling
- Caching considerations: Amazon DynamoDB Accelerator (DAX), Amazon ElastiCache and Valkey
• Large Scale (100,000+ patients)
- At large scale implement provisioned capacity with advanced partition key design (combining
facility/region
withPatientID
) to distribute high-volume workloads (refer to detailed examples in “DynamoDB Partition Key Design for High-Volume Deployments” section below) - Essential caching considerations: Compare DAX, Amazon ElasticCache and Valkey
- Consider Amazon DynamoDB Global Tables for resiliency and disaster recovery.
- Consider custom dashboards, monitor throttling events and automated scaling triggers alongside standard performance metrics.
DynamoDB Partition Key Design for High-Volume Deployments
As deployments scale, partition key design needs to be changed for performance. The current basic design (PartitionKey: PatientID, SortKey: Medication
) works for low volumes but requires enhancement for larger deployments. The following is the scaling strategy options for DynamoDB partition key design
- Basic (Current)
- Enhanced (Regional/Temporal)
Or
- Advanced (High Volume)
This design evolution ensures consistent performance as volume increases while maintaining query efficiency and avoiding hot partitions.
Cost Considerations
The following is a tabular breakdown of estimated costs for running this prescription validation solution at different scales in us-east-1 region
Scale | Monthly Patient Records |
DynamoDB Costs | Lambda Costs | Amazon Bedrock Costs (Agent + Knowledge Base queries) |
Total Estimated Monthly Cost |
Small | 1,000 patients;5,000 queries | $20-40(On-demand Capacity) | $5-15(~100,000 invocations) | $150-250 | $175-305 |
Medium | 10,000 patients;50,000 queries | $100-200(On-demand capacity) | $30-60(~1M invocations) | $1,000-1,500 | $1,130-1,760 |
Enterprise | 100,000 patients;500,000 queries | $800-1,200(Reserved capacityrecommended) | $200-400(~10M invocations) | $8,000-12,000 | $9,000-13,600 |
Cost Optimization Notes:
- DynamoDB costs can be reduced by switching from on-demand to provisioned capacity for predictable workloads
- Consider implementing Amazon DynamoDB Accelerator (DAX) for high-volume scenarios to reduce costs and improve performance
- Lambda costs can be optimized through function size and memory allocation tuning
- Bedrock costs represent the largest portion and scale with query volume; consider caching common responses.
Troubleshooting Guide:
This section outlines common issues you may encounter when deploying or running the prescription validation solution.
DynamoDB Access and Throttling Issues
- Check IAM roles for correct DynamoDB permissions
- Review CloudWatch logs for permission denied errors
- Verify table names and access patterns
- Refer Throttling issues for DynamoDB to troubleshoot DynamoDB throttling issues.
Bedrock Integration
- Validate Bedrock foundation model access configuration
- Check knowledge base accessibility
- Monitor API quotas and limits
Lambda Function Performance:
- Monitor memory utilization
- Check CloudWatch metrics for execution duration
Common Deployment Issues:
- Verify AWS service availability in chosen region
- Ensure sufficient AWS service quotas
- Review Terraform version compatibility
Limitations and further considerations
This implementation demonstrates prescription validation using a sample knowledge base, which serves as a proof of concept but requires significant enhancement for real-world use. Although the solution effectively checks drug interactions and maintains patient records, it currently relies on a limited dataset of medications and interaction rules. From a patient safety perspective, this solution would benefit from integration with Electronic Health Record (EHR) systems, either by receiving the PatientID directly from the EHR or, if used standalone, by displaying additional PII to verify correct patient selection. Furthermore, integrating with a FHIR-based clinical data repository would enhance the solution’s real-world applicability by enabling standardized access to comprehensive medication records.
Real-world implementation should address these considerations by integrating authorized drug information databases, implementing dosage-based severity assessments, and supporting real-time updates to interaction rules. For real-world implementations, organizations should utilize these options:
- FDA-approved commercial drug databases provide comprehensive, validated data with regular updates but require significant investment and complex integration.
- Public health sources (FDA National Drug Code Directory, RxNorm) offer free, standardized data but need more internal processing and maintenance.
- A hybrid approach can balance these tradeoffs by combining targeted commercial data with public sources for less-critical information.
As the patient database grows, several scalability considerations need to be addressed.
- For high-volume deployments, partition key design should evolve from basic
(PatientID)
to more sophisticated patterns likeRegionID#PatientID
orFacilityID#PatientID
to ensure consistent performance and avoid hot partitions (refer to detailed examples in “DynamoDB Partition Key Design for High-Volume Deployments” section above). - For real-world deployments handling thousands of concurrent requests, implementations should consider using caching for frequent queries.
- When choosing a caching solution, consider factors such as your workload patterns (read vs. write ratio), cost considerations, existing infrastructure, team expertise, and required cache control granularity.
- It’s important to evaluate different caching solutions based on your specific requirements. Options like Amazon ElastiCache and Valkey, offers serverless and additional features that may better suit certain customer needs.
Security considerations
When implementing this solution in a healthcare environment, several security measures must be considered to help ensure HIPAA compliance and protect sensitive patient data. The following are specific implementations and guidance
- IAM Policy Examples:
- Current Lambda Function DynamoDB Access: This policy follows least privilege principles, granting only the specific DynamoDB permissions needed for the Lambda function to operate.
- Data protection:
- Implement AWS Key Management Service (AWS KMS) with Customer Managed Keys (CMK) for Amazon Bedrock agent encryption.
- Apply data masking for personally identifiable information (PII) fields.
- This solution has Amazon Bedrock Guardrails enabled to mask PII (NAME, EMAIL, and SSN) and has model invocation logging enabled for logs.
- For example, if a healthcare provider inadvertently includes a patient’s name or email in their query, these will be masked in the response. Any attempt to input or retrieve a social security number will be blocked entirely, ensuring this sensitive information is never processed by the model.
- The system uses PatientID as the primary identifier in logs and responses, keeping medication details (dosage, frequency) visible while protecting sensitive patient identifiers.
- Access control:
- Set up KMS key policies with specific AWS service principals
- Use IAM policy conditions for fine-grained access control to DynamoDB
- DynamoDB encryption options and HIPAA compliance:
- HIPAA requires Protected Health Information (PHI) to be encrypted at rest and in transit:
- User data stored in DynamoDB is fully encrypted at rest by default using AWS owned keys. You can enable AWS KMS with CMK key types to encrypt your DynamoDB table at rest.
- DynamoDB encrypts data in transit by default using HTTPS.
- HIPAA audit trail implementation: HIPAA Security Rule mandates comprehensive auditing for Protected Health Information (PHI) access. The core requirement is maintaining detailed audit trails of all PHI interactions, including both successful and failed access attempts. Each access event must be logged with specific identifiers including the user’s identity, their exact actions, precise timestamps, access locations, and the specific records they accessed or attempted to access. AWS provides several built-in solutions to meet these comprehensive requirements.
- Built-in AWS Solutions and Their Use Cases:
- Basic Implementation (AWS CloudTrail + DynamoDB Streams)
- CloudTrail automatically logs all API calls while DynamoDB Streams captures table changes in real-time. This combination provides fundamental audit capabilities suitable for smaller deployments. It tracks who accessed what data, when changes occurred, and what modifications were made.
- Enhanced Implementation (Amazon CloudWatch + DynamoDB Point-in-Time Recovery)
- Combining CloudWatch with DynamoDB Point-in-Time Recovery enables detailed monitoring and provides a recoverable history of all table changes. This solution offers advanced querying capabilities and maintains a verifiable history of data changes, making it ideal for medium to large healthcare organizations. It supports automated alerts and compliance reporting through CloudWatch Metrics and Dashboards.
- Log Analysis and Reporting
- Amazon CloudWatch Logs Insights helps to analyze access patterns. Amazon OpenSearch enables advanced log searching and Amazon QuickSight creates compliance reports.
- Basic Implementation (AWS CloudTrail + DynamoDB Streams)
- Built-in AWS Solutions and Their Use Cases:
- HIPAA requires Protected Health Information (PHI) to be encrypted at rest and in transit:
Organizations implementing this solution should evaluate the following:
- Amazon DynamoDB data models for generative AI chatbots
- DynamoDB capacity planning for expected workloads
- Unlocking power of structured data with Amazon Bedrock Knowledge Bases
Conclusion
In this post, I showed you how to build a prescription validation system using Amazon Bedrock and DynamoDB. By using item collections in DynamoDB, you can create an efficient data model that keeps patient medications and interaction histories together. This solution enables healthcare providers to perform real-time prescription validation through natural language queries while maintaining data access and comprehensive audit trails. Read more about Using generative AI with DynamoDB in the AWS documentation.
About the authors
Aditya Ranjan is a Delivery Associate with Amazon Web Services, specializing in distributed systems architecture and cloud-native solutions. He collaborates with customers to design and implement well-architected technical solutions using the latest technologies from AWS, including generative AI services, enabling them to achieve their business goals and objectives.
Source: Read More