[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-83352":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":16,"stars7d":17,"stars30d":17,"stars90d":15,"forks30d":15,"starsTrendScore":18,"compositeScore":19,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":22,"hasPages":20,"topics":23,"createdAt":10,"pushedAt":10,"updatedAt":33,"readmeContent":34,"aiSummary":10,"trendingCount":15,"starSnapshotCount":15,"syncStatus":35,"lastSyncTime":36,"discoverSource":37},83352,"EHR-backend","harsh-vardhhan\u002FEHR-backend","harsh-vardhhan","EHR Annotation Platform","https:\u002F\u002Fd1pijuvgczqoi4.cloudfront.net\u002F",null,"TypeScript",62,10,51,0,8,11,24,62.72,false,"main",true,[24,25,26,27,28,29,30,31,32],"aws","aws-lambda","aws-s3","cloudformation","dynamodb","nestjs","s3","sam","sqs","2026-06-12 04:01:41","# EHR Annotation Platform - Backend\n\nEnterprise-grade serverless backend for clinical document annotation, built with Hono and deployed on AWS.\n\n> [!WARNING]\n> **Financial & Architectural Safeguard: Denial of Wallet (DoW) Protection**\n> \n> Unlike traditional servers (EC2, Render, Railway, etc.) that cap their financial damage by crashing under high load, AWS serverless applications scale **infinitely**.\n> \n> Under high virality or a **DDoS attack**, an unprotected serverless stack will spin up thousands of concurrent containers instantly. This can lead to **runaway AWS bills of hundreds of thousands of dollars overnight**.\n> \n> To mitigate this, this repository implements a custom **DDoS\u002FDoW Circuit Breaker**:\n> 1. **Zero-Base-Cost Function URLs** bypass API Gateway completely, eliminating gateway request charges ($3.50\u002FM) for blocked requests.\n> 2. **CloudWatch Alarm Metric Math** monitors total Lambda traffic (`Invocations + Throttles`) in a 1-minute window.\n> 3. **Lambda Concurrency Kill Switch** automatically triggers during an anomaly, programmatically throttling the API's reserved concurrency to `0` to drop subsequent request costs to exactly **$0.00**.\n\n## 🔗 Repository Links\n- **Backend**: [https:\u002F\u002Fgithub.com\u002Fharsh-vardhhan\u002FEHR-backend](https:\u002F\u002Fgithub.com\u002Fharsh-vardhhan\u002FEHR-backend)\n- **Frontend**: [https:\u002F\u002Fgithub.com\u002Fharsh-vardhhan\u002FEHR-frontend](https:\u002F\u002Fgithub.com\u002Fharsh-vardhhan\u002FEHR-frontend)\n\n## 🏗 AWS Architecture\n\nThe backend follows a highly scalable, serverless architecture designed for clinical data residency and high availability.\n\n```mermaid\ngraph TD\n    User((Clinician)) -->|API Request with API Key| LambdaURL[AWS Lambda Function URL]\n    LambdaURL -->|Hono Router & Auth Middleware| LambdaAPI[AWS Lambda - API]\n    LambdaAPI -->|Read\u002FWrite| DynamoDB[(Amazon DynamoDB)]\n    LambdaAPI -->|Read| S3[(Amazon S3 - Medical Notes)]\n    LambdaAPI -->|Manual Trigger| SQS[AWS SQS - Annotation Queue]\n\n    S3 -->|Emit Event| EB[Amazon EventBridge - Bus]\n    EB -->|Route Rule| SQS[AWS SQS - Annotation Queue]\n    SQS -->|Trigger| LambdaWorker[AWS Lambda - NLP Worker]\n    SQS -.->|Failures| DLQ[AWS SQS - Dead Letter Queue]\n    \n    LambdaWorker -->|Inference| Groq[Groq AI - LLM Inference]\n    LambdaWorker -->|Save Annotations| DynamoDB\n\n    %% DDoS Protection\n    LambdaAPI -.->|Invocations & Throttles| CWAlarm[CloudWatch Traffic Alarm]\n    CWAlarm -->|Trigger if >200 req\u002F1m| SNS[SNS Topic]\n    SNS -->|Invoke| LambdaKillSwitch[AWS Lambda - Kill Switch]\n    LambdaKillSwitch -->|Set Reserved Concurrency to 0| LambdaAPI\n```\n\n### Infrastructure Components\n\n| Component | Role in Architecture |\n| :--- | :--- |\n| **AWS Lambda (API)** | Executes the Hono application, handling UI interactions and document metadata orchestration. |\n| **AWS Lambda (NLP Worker)** | Dedicated asynchronous worker triggered by SQS to perform LLM clinical entity extraction. |\n| **AWS Lambda (Kill Switch)** | Administrative helper triggered by SNS to throttle the API Lambda reserved concurrency to 0. |\n| **Amazon SQS & DLQ** | Decouples document ingestion from analysis, buffers surges, and quarantines failed tasks in a Dead Letter Queue. |\n| **Amazon DynamoDB** | Managed NoSQL storage for ultra-low latency storage of clinical annotation metadata and document status. |\n| **Amazon S3** | Encrypted object storage for raw clinical document text, acting as the event source for the ingestion pipeline. |\n| **Lambda Function URL** | Public HTTPS endpoint routing requests directly to the Hono backend. |\n| **CloudWatch Alarm & SNS** | Monitors total request volume (Invocations + Throttles) in real-time, acting as the circuit breaker sensor. |\n| **Groq AI Integration** | High-performance inference engine running clinical entity recognition models. |\n\n## 🗄️ DynamoDB Single-Table Design\n\nTo maximize performance, cut database costs, and eliminate cross-table JOIN latency, this application uses a consolidated **Single-Table Design** layout (`EhrTable`) instead of traditional relational multi-table structures.\n\n### Key Schema Layout\n\n| PK (Partition Key) | SK (Sort Key) | Entity Type | Attributes & Schema |\n| :--- | :--- | :--- | :--- |\n| `DOCUMENT#\u003CdocId>` | `METADATA` | **Document** | `id`, `title`, `category`, `s3Key`, `status`, `createdAt` |\n| `DOCUMENT#\u003CdocId>` | `ANNOTATION#\u003CannotationId>` | **Annotation** | `annotationId`, `documentId`, `text`, `label`, `startOffset`, `endOffset`, `createdAt`, `source`, `status`, `confidence` |\n\n### Query Optimizations\n\n1. **Unified Read (Document + Annotations):** \n   When opening a patient note, the backend executes a single DynamoDB query where `PK = DOCUMENT#\u003CdocId>`. This retrieves the document metadata and all its annotations in a **single physical database operation**, reducing network roundtrips and latency by 50%.\n2. **Inverted Index (`SKIndex`):**\n   To update or delete an annotation by its `annotationId` alone (without knowing the parent `documentId`), we use a Global Secondary Index (GSI) called `SKIndex` (where `HashKey = SK` and `RangeKey = PK`). This resolves the parent `PK` in milliseconds, allowing targeted, isolated edits on specific rows.\n\n## 🚀 CI\u002FCD Pipeline\n\nThe project uses GitHub Actions for an automated, zero-downtime deployment workflow.\n\n| Pipeline Stage | Processes | Actions & Best Practices | Trigger Event |\n| :--- | :--- | :--- | :--- |\n| **Continuous Integration (CI)** | • Linting\u003Cbr>• Type Checking | Runs automated TypeScript linting and strict compilation checks. | All Pull Requests targeting `main` |\n| **Continuous Deployment (CD)** | • Build & Bundle\u003Cbr>• AWS SAM Deploy\u003Cbr>• OIDC Authentication\u003Cbr>• Env Variable Sync | Bundles files using `esbuild`, provisions CloudFormation stacks, signs in passwordlessly using OpenID Connect (OIDC), and syncs secrets. | Every commit\u002Fmerge push to `main` |\n\n\n## 🛡️ Denial of Wallet (DoW) & DDoS Protection\n\nThis backend incorporates a robust, multi-layered security architecture designed to prevent volumetric DDoS abuse and cloud-native **Denial of Wallet (DoW)** attacks, guaranteeing predictable operational billing.\n\n| Defense Vector | Implementation & Controls | Purpose & Billing Safety Impact |\n| :--- | :--- | :--- |\n| **Auth Gatekeeper** | Valid `x-api-key` header verified in Hono middleware. | Rejects unauthenticated requests in ~2ms before executing database operations. |\n| **Zero-Routing Cost Gateway** | Direct Lambda Function URL (no API Gateway request fees). | Eliminates API Gateway per-request charges ($3.50\u002Fmillion), ensuring throttled requests cost exactly $0.00. |\n| **Automated Circuit Breaker** | CloudWatch Alarm (>200 req\u002F1m) $\\rightarrow$ SNS $\\rightarrow$ Kill-Switch Lambda. | Automatically updates backend Lambda reserved concurrency to `0` on breach, dropping resource billing to absolute zero. |\n| **Compute Scaling Caps** | `ReservedConcurrentExecutions` limits (**5** for API Lambda, **2** for SQS NLP Worker). | Caps the maximum number of concurrent running containers AWS can spin up under a flood. |\n| **Asynchronous Decoupling** | SQS-backed queue hand-off (`EhrAnnotationQueue`) with `BatchSize: 5`. | Prevents container runtime crashes; processes spikes in document uploads sequentially rather than in parallel. |\n| **Infinite Retry Defense** | SQS Dead Letter Queue (`EhrAnnotationDLQ`) with `maxReceiveCount: 3`. | Quarantines failing payloads (poison pills) to prevent endless execution retry loops. |\n| **Partial Batch Isolation** | SQS batch response processing with `ReportBatchItemFailures`. | Prevents successfully processed records in a batch from being re-executed when a sibling record in the same batch fails, saving redundant LLM API costs. |\n| **External API Timeouts** | Groq NLP call `AbortController` (strictly capped at **8 seconds**). | Prevents hung external LLM endpoints from keeping the worker Lambda running up to its 30-second cap. |\n| **Database Cost Ceiling** | DynamoDB table configured with provisioned capacity (**5 RCU \u002F 5 WCU**). | Acts as a budget boundary, preventing database scaling costs from skyrocketing during attacks. |\n| **Compute Efficiency** | Parallel database writes via `Promise.all` instead of sequential writes. | Grouped DB actions run concurrently, reducing billable Lambda active execution time by over 80%. |\n| **S3 Read-Only Worker** | SQS Lambda worker has read-only S3 permissions (`S3ReadPolicy`) and never writes back to S3. | There is zero risk of an infinite S3 write-event loop. |\n| **Agentic Role Scoping** | Dev policy (`developer-policy.json`) restricts agent actions to data-plane only (S3\u002FDynamoDB item actions) and read-only infra visibility. | Prevents AI agent hallucinations or runaway CLI scripts from deleting infrastructure or provisioning expensive, untracked resources. |\n\n> [!TIP]\n> **Manual Recovery after Circuit Breaker Activation:**\n> To bring the system back online after a kill-switch trigger, reset the backend Lambda's reserved concurrency back to your desired capacity (e.g., `5` or delete the limit) via the AWS Console, AWS SDK\u002FCLI, or by redeploying the SAM template.\n\n## 🛠 Local Development\n\n### Prerequisites\n- Node.js 20+\n- AWS CLI (configured via AWS IAM Identity Center\u002FSSO profile e.g., `ehr-dev`)\n- SAM CLI (optional, for local Lambda emulation)\n\n### Setup\n```bash\n$ npm install\n```\n\n### Running Locally\n```bash\n# development\n$ npm run start:dev\n```\n\n## 📜 Key Scripts\n- `npm run build`: Compiles the application.\n- `npm run bundle`: Creates a production-ready esbuild bundle for AWS Lambda.\n- `npm run lint`: Runs the linter.\n- `npm run test`: Executes unit tests.\n- `npm run cleanup`: Wipes all DynamoDB table items and S3 objects to reset the environment.\n- `npm run seed`: Seeds the S3 bucket with sample document notes.\n\n---\n*Built for the Modern Clinical Workflow.*\n",2,"2026-06-11 04:11:01","CREATED_QUERY"]