Pharmacy Intelligence Platform

Multi-Store Intelligence Layer
for Retail Pharmacy Chains

End-to-end architecture for 313 pharmacies โ€” real-time KPI dashboards, demand forecasting, AI chatbot, and cloud cost optimisation across AWS, Azure, and GCP.

313
Pharmacies
7 GB
Per Store MySQL
~2.2 TB
Total Data
266K
Max Daily Txns
54.5M
Max Yearly Records
10 yrs
Historical Depth

๐Ÿ“Š Data Volume Profile

Single Store (Average Performer)

TableDaily MinDaily MaxYearly Max
vw_all_sales282850174,030
sale_items282850174,030
sales13231360,649
purchaseโ€”162,029

Current MySQL size: 7 GB ยท 10 years of history

All 313 Pharmacies (Chain-Wide)

TableDaily MinDaily MaxYearly Max
vw_all_sales88,266266,05054,471,390
sale_items88,266266,05054,471,390
sales41,31697,96918,983,137
purchaseโ€”5,008635,077

Total data: ~2.2 TB ยท Annual growth: ~220 GB/yr

Ingestion Rate
~3 rows/sec
Peak across all stores
ETL Approach
CDC + Batch
Change data capture nightly
Storage Tier
Hot / Warm
2yr hot, 8yr warm/archive
Format at Rest
Parquet
~70% compression vs raw SQL

๐Ÿ— System Architecture

Five-layer architecture: Store Edge โ†’ Ingestion โ†’ Data Lake โ†’ Intelligence โ†’ Presentation. Designed to be cloud-agnostic at the storage and compute layers.

Layer 1 โ€” Store Edge (313 Stores)
๐Ÿช
MySQL / POS
Sales, Inventory, Purchase
โ†’
๐Ÿ”„
CDC Agent
Debezium / custom connector
โ†’
๐Ÿ”’
VPN / TLS
Encrypted tunnel to cloud
โ†“
Layer 2 โ€” Ingestion & Streaming
๐Ÿ“จ
Kinesis / Kafka
AWS MSK / Azure Event Hub / GCP Pub/Sub
โ†’
โšก
Lambda / Functions
Validate, deduplicate, enrich
โ†’
๐Ÿ—‚
Raw Landing Zone
S3 / ADLS / GCS โ€” Parquet/ORC
โ†“
Layer 3 โ€” Data Lake & Warehouse
๐Ÿ”
Bronze Layer
Raw CDC events
โ†’
๐Ÿช™
Silver Layer
Cleaned, store-partitioned
โ†’
๐Ÿฅ‡
Gold Layer
KPI aggregates, mart tables
โ†’
๐Ÿ”
Query Engine
Athena / Synapse / BigQuery
โ†“
Layer 4 โ€” Intelligence (AI/ML)
๐Ÿ“ˆ
Demand Forecast
Prophet / XGBoost per SKU
๐Ÿšจ
Anomaly Detection
Isolation Forest โ€” stock outs
๐Ÿ›’
Basket Analysis
Apriori / FP-Growth rules
๐Ÿค–
AI Chatbot
LLM + RAG on KPI store
๐Ÿ“ฆ
Reorder Engine
Auto PO suggestions
โ†“
Layer 5 โ€” Presentation
๐Ÿ“Š
KPI Dashboard
React + Recharts (your current)
๐Ÿ“ฑ
Mobile App
Store manager view
๐Ÿ’ฌ
Chatbot UI
Web widget + WhatsApp
๐Ÿ“ง
Alerts
Email / SMS / WhatsApp
๐Ÿ“‘
Reports
Scheduled PDF exports

โš™๏ธ Data Pipeline Design

๐Ÿ”„ Ingestion Strategy

  • 1
    Nightly Batch Pull (Primary) โ€” Cron at 2 AM pulls delta from each store's MySQL using last-modified timestamps. Safest for existing POS systems.
  • 2
    CDC via Debezium โ€” For stores with binlog enabled, real-time change capture gives near-realtime dashboard updates (15โ€“30 min lag).
  • 3
    Manual Upload Fallback โ€” Stores with connectivity issues upload CSV dumps via secure portal. ETL handles dedup.

๐Ÿงน Transformation Rules

  • 1
    Deduplication โ€” Hash on (store_id, bill_no, item_id, txn_date) to prevent double-counting during retries.
  • 2
    Drug Master Mapping โ€” Normalise SKU names across stores (generic vs branded, spelling variants).
  • 3
    Partitioning โ€” Partition Parquet files by (year / month / store_id) for optimal Athena / BigQuery scan costs.
  • 4
    Aggregation โ€” Pre-compute daily, weekly, monthly KPI rollups to sub-second dashboard response.

Pipeline Flow

๐Ÿช
Store MySQL
313 instances
โ†’
๐Ÿ“ก
Collector Agent
Python / Debezium
โ†’
๐Ÿ“จ
Message Queue
SQS / Pub/Sub
โ†’
โœ…
Validator
Lambda / Cloud Fn
โ†’
๐Ÿ”
Bronze Lake
Raw Parquet on S3
โ†’
โš—๏ธ
Glue / dbt
Transform + clean
โ†’
๐Ÿฅ‡
Gold Mart
KPI aggregates
โ†’
๐Ÿ”
Athena/BQ
Ad-hoc query
โ†’
๐Ÿ“Š
Dashboard API
FastAPI + Cache

๐Ÿค– ML Models Planned

Demand ForecastProphet / XGBoost
Stockout PredictionLSTM
Basket AnalysisFP-Growth
Price ElasticityRegression
Churn Risk (stores)Gradient Boost

๐Ÿ—„ Storage Sizing (Total Chain)

Raw MySQL exports2.2 TB
Parquet compressed~660 GB
Gold KPI aggregates~50 GB
ML model artifacts~20 GB
Annual growth~150 GB/yr

โšก KPI Targets

Dashboard load< 2 sec
Data freshness< 4 hrs
Chatbot response< 3 sec
ML prediction run< 2 hrs
Platform uptime99.5%

๐Ÿ’ฌ AI Chatbot Architecture

A RAG-powered chatbot that lets pharmacists, store managers, and HQ staff query business data in plain English โ€” via web widget or WhatsApp.

Query Flow

  • 1
    User Input โ€” "Show me top 10 slow-moving drugs in store #45 this month" via chat widget or WhatsApp.
  • 2
    Intent Classification โ€” LLM classifies: KPI query / forecast query / reorder alert / general drug info.
  • 3
    SQL Generation (Text-to-SQL) โ€” GPT-4o / Gemini converts natural language to SQL against your Gold layer schema.
  • 4
    Query Execution โ€” Generated SQL runs on Athena / BigQuery against pre-aggregated KPI tables. Results in <1 sec for Gold layer.
  • 5
    Response Synthesis โ€” LLM formats result as natural language + optional chart data payload.
  • 6
    Delivery โ€” Response sent back via web widget with inline mini-chart, or WhatsApp text summary.

Chatbot Capabilities

๐Ÿ“Š Analytics Queries

"What are my top 5 selling brands across all stores today?" ยท "Which store has the highest average basket size?"

โš ๏ธ Alerts & Anomalies

"Any stores with unusually low sales today?" ยท "Which drugs are about to go out of stock in Ernakulam stores?"

๐Ÿ”ฎ Forecasts

"What will Paracetamol demand look like next 30 days?" ยท "Suggest reorder quantities for store #12."

๐Ÿ“‹ Reports

"Give me a daily summary for all stores" ยท "Export this month's purchase report as PDF."

๐Ÿ”ง Tech Stack Options

LLM CoreGPT-4o / Gemini 1.5
Text-to-SQLLangchain + few-shot
Vector StorePinecone / pgvector
FrameworkFastAPI backend
WhatsAppMeta Cloud API

๐Ÿ›ก Safety & Guardrails

  • โœ… Role-based: Store managers see only their store data
  • โœ… SQL injection prevention via parameterised queries
  • โœ… Max row limit: 10K per query to prevent abuse
  • โœ… Query cost cap via Athena workgroup limits
  • โœ… Audit log of all chatbot queries per user

๐Ÿ’ฐ Chatbot Cost/Month

GPT-4o (1K queries/day)~$90
Gemini 1.5 Flash (alt)~$12
Vector DB (Pinecone)~$70
WhatsApp API (500 msg)~$3
Hosting (FastAPI)included

๐Ÿ’ฐ Multi-Cloud Cost Estimator

Adjust the sliders to model cost for different scale scenarios. All prices are based on ap-south-1 (AWS Mumbai), Central India (Azure), and asia-south1 (GCP Mumbai) regions.

313
566
500
100

Detailed Breakdown

Component AWS ($/mo) Azure ($/mo) GCP ($/mo) Notes
TOTAL / MONTH โ€” โ€” โ€”
TOTAL / YEAR โ€” โ€” โ€”
โš ๏ธ Estimation Notes: Costs are approximations based on public pricing (June 2025, South Asia regions). Actual costs vary with reserved instance discounts (up to 60%), committed use discounts, negotiated enterprise agreements, and data egress patterns. AWS and Azure prices based on ap-south-1 and Central India respectively. GCP based on asia-south1. Always run cloud provider calculators for production budgeting.

โš–๏ธ Cloud Provider Comparison

Capability AWS Azure GCP
Data LakeS3 + Glue + AthenaADLS Gen2 + SynapseGCS + Dataflow + BigQuery
Serverless ComputeLambda + Step FunctionsAzure Functions + Logic AppsCloud Functions + Workflows
ML PlatformSageMakerAzure MLVertex AI
StreamingKinesis / MSKEvent HubsPub/Sub + Dataflow
Managed DBAurora ServerlessAzure SQL ServerlessAlloyDB / Cloud SQL
CDN / API GWCloudFront + API GWAzure CDN + APIMCloud CDN + Apigee
India PresenceMumbai (ap-south-1)Central IndiaMumbai (asia-south1)
MySQL MigrationDMS (native MySQL)Database Migration ServiceDatabase Migration Service
AI/LLM AccessBedrock (Claude, Titan)Azure OpenAI (GPT-4o)Vertex AI (Gemini)
Best For This Projectโœ… Strong all-round, mature ecosystemโš ๏ธ Best if already in Microsoft stackโœ… Best BI / BigQuery pricing

๐Ÿ† Recommendation

Recommended for Scale

AWS โ€” Primary Choice

Lambda + S3 + Athena + Aurora Serverless. Mumbai region. Best mature ecosystem for this use case. Your existing AWS cost calculator shows $300/mo for prediction layer alone โ€” add ~$200 for ingestion, storage, and dashboard = ~$500/mo total.

โœ… Recommended: Lambda architecture (Design A) at your current scale

Best for Analytics

GCP โ€” Analytics-Heavy Builds

BigQuery is significantly cheaper for ad-hoc analytics vs Athena at scale. Vertex AI + Gemini gives native LLM integration. Consider GCP if your primary workload is querying and BI, not heavy ML training.

BigQuery: $5/TB scanned vs Athena $5/TB โ€” similar, but BQ has flat-rate options

If Microsoft-First

Azure โ€” Microsoft Ecosystem

Best if client already uses Microsoft 365, Dynamics, or Power BI. Azure Synapse + Power BI Embedded gives excellent out-of-box dashboards. Higher baseline cost but good enterprise support in India.

โš ๏ธ Typically 15โ€“25% more expensive than AWS/GCP for this workload

๐Ÿ—บ Implementation Roadmap

Phase 1

Foundation

  • Cloud account + VPC setup
  • Data migration: 10yr MySQL โ†’ S3 Parquet
  • Bronze/Silver/Gold lake structure
  • ETL pipeline (nightly batch)
  • Basic dashboard API
โฑ 6โ€“8 weeks
Phase 2

KPI Layer

  • KPI aggregation tables
  • Dashboard (your existing UI)
  • Multi-store filtering
  • User auth + RBAC
  • Alerting (email/SMS)
โฑ 4โ€“6 weeks
Phase 3

Intelligence

  • Demand forecast (Prophet)
  • Stockout prediction
  • Reorder suggestion engine
  • Basket analysis
  • Anomaly detection
โฑ 6โ€“8 weeks
Phase 4

AI Chatbot

  • LLM + Text-to-SQL pipeline
  • Web widget integration
  • WhatsApp Business API
  • Store-level RBAC in bot
  • Feedback + fine-tuning loop
โฑ 4โ€“6 weeks
๐Ÿ’ก Total Timeline: 20โ€“28 weeks (5โ€“7 months) for full platform. Phase 1+2 alone delivers immediate ROI โ€” stakeholders can see chain-wide KPIs within 10โ€“14 weeks. Budget Phase 1โ€“2: ~โ‚น15โ€“20 lakhs development + $500/mo cloud. Full platform: ~โ‚น35โ€“50 lakhs + $800โ€“1200/mo cloud.