Prompt Details
Model
(claude-5-5-sonnet)
Token size
5,840
Example input
[Provide the GraphQL schema, important types, fields, relationships, directives, operation types, gateway architecture, and GraphQL implementation framework.]: A healthcare platform exposes GraphQL operations for appointments, clinician schedules, patient records, laboratory results, and billing summaries. A federated gateway connects separate clinical and scheduling services.
[Describe resolver implementations, database access, downstream APIs, data loaders, caching, batching, synchronous work, and expensive operations.]: Resolvers retrieve appointment data from a scheduling database, laboratory results from a clinical service, and billing information from a financial service. Some calls may run in parallel; actual batching behavior is unknown
[Provide representative queries, common operations, nesting patterns, pagination arguments, aliases, fragments, query frequency, and expected concurrency.]: Typical operations include daily appointment dashboards, clinician availability searches, patient history retrieval, and administrative reporting. Some queries request multiple months of records.
[Describe users and tenants, shared infrastructure, database capacity, downstream service quotas, traffic expectations, service objectives, and isolation requirements.]: Multiple healthcare organizations share the platform. Patient records must remain isolated by organization and authorized user. Clinical services have independent capacity and availability constraints.
[Provide target limits, acceptable error behavior, technology restrictions, rollout deadlines, backward-compatibility requirements, and measurable success criteria.]: Reduce expensive queries, protect clinical services, preserve authorized workflows, maintain tenant isolation, and introduce controls without disrupting patient care.
Example output
### 🔍 Phase 1: Execution Context Reconstruction
Test ID: HC-01
Scenario: A clinician opens a dashboard containing today's appointments and recent laboratory results.
Analysis:
* The gateway receives the GraphQL operation.
* Authentication and organization context are established.
* The document and its arguments are validated.
* Query cost and service-specific budgets are evaluated.
* Authorization is checked for the requested patient data.
* Scheduling and clinical resolvers retrieve the required records.
* The gateway assembles the response and records telemetry.
Expected findings:
* The federated gateway introduces multiple service boundaries.
* A single GraphQL operation may generate requests to several services.
* Clinical data authorization must be enforced independently of complexity scoring.
* The real gateway implementation and execution plan remain unknown.
Result: ⚠️ Conditional pass. The architecture is modeled, but the actual deployment requires inspection.
### 🧩 Phase 2: Schema Complexity and Resource Amplification
Test ID: HC-02
Consider this illustrative query:
```graphql
query ClinicianDashboard {
appointments(first: 40) {
id
startTime
patient {
id
recentLabResults(first: 15) {
testName
status
}
}
}
}
```
Potential amplification:
* Up to 40 appointment records.
* Up to 15 laboratory results per appointment's patient.
* Up to 600 result selections before accounting for repeated patients, deduplication, or batching.
This is an upper bound on selected result records under the stated assumptions, not a prediction of database queries or service calls.
| Risk ID | Potential risk | Recommended control |
| --------- | ------------------------------------- | ------------------------------------------- |
| HC-SCH-01 | Repeated patient-history retrieval | Request-scoped batching where appropriate |
| HC-SCH-02 | Excessive laboratory-result expansion | Bound nested pagination |
| HC-SCH-03 | Federated-service fan-out | Measure downstream call counts |
| HC-SCH-04 | Oversized clinical responses | Apply response-size and query-cost controls |
Result: ⚠️ Conditional pass. The amplification path is identifiable, but actual service cost must be measured.
### 🧮 Phase 3: Complexity Scoring Model
Test ID: HC-03
Create a provisional scoring model for clinical dashboard operations.
Illustrative cost assignments:
* Scalar field: 1 unit.
* Object resolver: 3 units.
* Laboratory-result list resolver: 8 units plus child-selection costs multiplied by validated cardinality.
* Cross-service lookup: an additional provisional cost based on measured downstream work when available.
These numbers are test fixtures, not measured healthcare-system costs.
Validation steps:
* Score a simple appointment query.
* Score the nested laboratory-result query.
* Compare costs for different validated page sizes.
* Account for repeated aliases and fragments.
* Compare predictions with service latency, database work, and response size.
* Version the scoring model so schema changes trigger recalibration.
Pass criteria: The model assigns repeatable costs and identifies expensive cross-service queries without rejecting legitimate operations excessively.
Result: ⚠️ Calibration required.
### 📏 Phase 4: Depth, Pagination and Request-Shape Governance
Test ID: HC-04
Illustrative test configuration:
| Control | Test setting |
| ----------------------------- | ---------------- |
| Maximum query depth | 7 |
| Maximum list page size | 50 |
| Maximum request body | 128 KB |
| Maximum aliases | 15 |
| Maximum calculated complexity | To be calibrated |
These are sample settings, not validated production thresholds.
Test cases:
* Request 20 appointments: eligible for further validation.
* Request 51 items from a list capped at 50: reject.
* Supply a negative pagination value: reject.
* Omit required pagination arguments: reject or use a documented safe default.
* Submit a query with many aliases: account for the actual execution work.
* Submit an excessively large request: reject before resolver execution.
Healthcare-specific requirement: Limits must not silently make essential clinical workflows unusable. Any exception should be authorized, narrowly scoped, and monitored.
Result: ✅ Policy design passes; enforcement remains untested.
### ⚙️ Phase 5: Resolver Cost and Backend Workload
Test ID: HC-05
| Resolver area | Potential failure | Investigation |
| ------------------- | --------------------------- | ------------------------------------------- |
| Appointment search | Expensive date-range scans | Inspect query plans and indexes |
| Patient history | Repeated record retrieval | Measure resolver invocations |
| Laboratory results | Downstream service fan-out | Measure calls and latency |
| Clinician schedules | Large availability searches | Evaluate filters and pagination |
| Billing summary | Slow aggregation | Inspect query execution and caching options |
Test procedure:
* Trace each resolver.
* Count database queries and downstream calls.
* Compare serial and bounded-parallel execution.
* Inspect connection-pool utilization.
* Test batching with repeated patient references.
* Verify cancellation when a request times out.
Result: ⚠️ Evidence required. The skill identifies the relevant measurements without inventing performance gains.
### 🗄️ Phase 6: Database and Downstream Resource Protection
Test ID: HC-06
Scenarios:
* A clinician requests a broad historical date range.
* Several dashboards request laboratory results simultaneously.
* The clinical service becomes slow.
* The scheduling database approaches connection-pool exhaustion.
* A downstream service times out during a federated operation.
Required controls:
* Database statement timeouts.
* Bounded connection pools.
* Per-service concurrency limits.
* Request deadlines and cancellation propagation.
* Bounded date ranges and pagination.
* Circuit breakers or equivalent failure controls where supported.
* Monitoring of service latency, error rates, and resource pressure.
Pass criteria: A costly or stalled operation cannot consume unlimited resources or cause uncontrolled downstream request accumulation.
Result: ⚠️ Conditional pass. The design is appropriate, but real service configurations have not been tested.
### 🚦 Phase 7: Query Budgets and Admission Control
Test ID: HC-07
Proposed admission sequence:
* Authenticate the caller.
* Establish organization and user identity.
* Validate document size and syntax.
* Validate the schema and arguments.
* Calculate operation complexity.
* Check pagination and date-range constraints.
* Check tenant and service-specific budgets.
* Verify authorization for every requested data scope.
* Apply concurrency controls.
* Admit or reject the request and record the decision.
Test scenarios:
* Authorized, low-cost appointment query: admit if all policies pass.
* Excessively expensive history query: reject before expensive work.
* Unauthorized patient record request: deny regardless of its cost.
* Clinical service unavailable: return a controlled error or permitted partial result according to the API contract.
Result: ✅ Design passes. Authentication, authorization, and service-failure handling still require implementation tests.
### 🛡️ Phase 8: Rate Limiting, Fairness and Multi-Tenant Governance
Test ID: HC-08
Scenario: One healthcare organization submits a large volume of historical-record requests while another organization uses ordinary scheduling queries.
Expected behavior:
* Each organization has an appropriately configured resource budget.
* Expensive operations consume more budget than lightweight operations.
* Global controls protect shared infrastructure.
* A tenant reaching its quota does not automatically exhaust other tenants' capacity.
* Legitimate high-priority clinical workflows receive only explicitly configured and auditable exceptions.
Recommended controls:
* Identity-aware rate limits.
* Complexity-weighted budgets.
* Per-tenant concurrency caps.
* Service-specific quotas.
* Burst controls and retry backoff.
* Audited priority policies.
Result: ⚠️ Simulation required. Fairness must be validated using concurrent multi-tenant tests.
### 🔐 Phase 9: Abuse Resistance and Adversarial Analysis
Test ID: HC-09
| Test ID | Scenario | Expected result |
| -------- | -------------------------------------------- | ----------------------------------------- |
| HC-AB-01 | Deeply nested patient-history query | Reject if policy limits are exceeded |
| HC-AB-02 | Large nested laboratory-result lists | Enforce cardinality and complexity limits |
| HC-AB-03 | Repeated aliases targeting costly fields | Account for execution cost |
| HC-AB-04 | Fragment-heavy operation | Calculate expanded selection cost |
| HC-AB-05 | Excessive historical date range | Enforce documented range restrictions |
| HC-AB-06 | Unauthorized patient identifier | Deny access |
| HC-AB-07 | Repeated requests to a slow clinical service | Apply rate and concurrency limits |
| HC-AB-08 | Cross-organization record access | Deny unauthorized access |
Security distinction: A high-cost query is not necessarily malicious, and a low-cost query is not necessarily authorized.
Result: ✅ Test plan passes. No actual vulnerability has been established by this simulation.
### 🧪 Phase 10: Complexity Calibration and Testing
Test ID: HC-10
| Test ID | Scenario | Expected outcome |
| -------- | ------------------------------------------------- | ------------------------------------ |
| HC-TC-01 | Single appointment lookup | Accept if authorized |
| HC-TC-02 | Paginated daily schedule | Accept within budget |
| HC-TC-03 | Nested laboratory-result query | Apply calculated cost |
| HC-TC-04 | Invalid pagination | Reject |
| HC-TC-05 | Repeated aliases | Count applicable execution cost |
| HC-TC-06 | Broad historical query | Enforce date-range and cost policies |
| HC-TC-07 | Slow downstream clinical service | Enforce deadlines and concurrency |
| HC-TC-08 | Simultaneous requests from multiple organizations | Preserve resource budgets |
| HC-TC-09 | Unauthorized patient record | Deny |
| HC-TC-10 | Complexity estimator unavailable | Follow explicit failure policy |
Pass criteria:
* No pagination bypass.
* Correct alias and fragment accounting.
* Unauthorized records remain inaccessible.
* Resource use remains bounded during concurrency.
* False positives and false negatives are measured.
* Complexity predictions are compared with actual execution data.
Result: ⚠️ Awaiting execution. These are test specifications, not completed runtime tests.
### 📊 Phase 11: Observability and Cost Attribution
Test ID: HC-11
Capture:
* Operation fingerprint and identifier.
* Calculated complexity and admission outcome.
* Resolver execution time.
* Scheduling and clinical service latency.
* Database query duration.
* Downstream call counts.
* Response payload size.
* Timeout and error rates.
* In-flight requests by service.
* Tenant budget consumption.
Alert examples:
* Sudden increase in expensive patient-history operations.
* Rising clinical-service timeout rates.
* Sustained database connection-pool pressure.
* Unexpected tenant quota exhaustion.
* A growing difference between estimated and measured operation cost.
Privacy controls: Avoid logging patient names, raw clinical values, or unnecessary identifying query variables. Use appropriately protected identifiers and access-controlled telemetry.
Result: ✅ Design passes; telemetry implementation requires verification.
### 🔄 Phase 12: Caching, Persisted Queries and Optimization
Test ID: HC-12
Evaluation plan:
* Measure whether repeated schedule queries benefit from caching.
* Check whether batching reduces repeated patient lookups.
* Validate cache keys across organizations and authorization scopes.
* Test invalidation after appointment changes.
* Verify that persisted operations still undergo applicable authorization and resource checks.
* Measure behavior when a downstream service is unavailable.
Expected outcome: Reduce unnecessary work where measurements justify optimization, without serving stale or unauthorized clinical information.
Important constraint: Clinical data may require stricter freshness rules than ordinary catalog data. Cache policy must reflect the actual data-consistency requirements.
Result: ⚠️ Conditional pass. Benefits and safe cache durations have not been established.
### ⚖️ Phase 13: Failure Modes and Governance Trade-offs
Test ID: HC-13
| Risk ID | Failure mode | Mitigation |
| --------- | ---------------------------------- | ------------------------------------------------------- |
| HC-GOV-01 | Essential clinical query rejected | Measure false positives and validate critical workflows |
| HC-GOV-02 | Expensive query underestimated | Calibrate against service-level traces |
| HC-GOV-03 | Clinical service timeout | Bound concurrency and enforce deadlines |
| HC-GOV-04 | Cross-tenant authorization failure | Validate organization-level access boundaries |
| HC-GOV-05 | Policy service unavailable | Define explicit failure behavior |
| HC-GOV-06 | Stale clinical data returned | Apply data-specific cache invalidation rules |
| HC-GOV-07 | Overly broad privileged exception | Require approval, scope, and audit logging |
| HC-GOV-08 | Schema changes invalidate costs | Run regression tests after schema changes |
Trade-off: Aggressive limits may protect shared services but disrupt legitimate care-related workflows. More permissive limits preserve flexibility but can increase resource pressure. Thresholds should be based on evidence and operational requirements.
Result: ✅ Risk register passes; mitigations require validation.
### 🗺️ Phase 14: Governance Policy and Implementation Blueprint
Test ID: HC-14
| Policy ID | Policy | Enforcement point |
| --------- | ----------------------------------- | --------------------------------------------- |
| HC-POL-01 | Request-size limits | Gateway or HTTP middleware |
| HC-POL-02 | Schema and argument validation | GraphQL validation pipeline |
| HC-POL-03 | Complexity calculation | Pre-execution validation |
| HC-POL-04 | Pagination and date-range limits | Argument validation |
| HC-POL-05 | Organization-specific budgets | Admission-control layer |
| HC-POL-06 | Clinical-service concurrency limits | Federated gateway and service boundaries |
| HC-POL-07 | Patient-data authorization | Trusted authorization layer |
| HC-POL-08 | Database execution limits | Database driver and database configuration |
| HC-POL-09 | Audit and cost telemetry | Gateway and resolver instrumentation |
| HC-POL-10 | Persisted-operation controls | Operation registration and execution pipeline |
Illustrative pseudocode:
```python
def govern_clinical_query(request, context):
authenticate(request, context)
establish_organization_scope(context)
validate_request_size(request)
validate_graphql_document(request)
validate_arguments(request)
authorize_requested_data(request, context)
cost = calculate_complexity(request)
enforce_pagination_and_date_limits(request)
enforce_tenant_budget(context, cost)
enforce_service_budgets(request, cost)
enforce_concurrency_limits(context)
record_decision(request, cost)
return execute_with_deadlines(request, context)
```
This pseudocode illustrates the control flow. Production implementation must account for the selected framework, authorization architecture, and approved clinical failure behavior.
Result: ✅ Blueprint passes at the design level.
### 🛠️ Phase 15: Rollout and Continuous Governance
Test ID: HC-15
Stage A — Observe
Inventory clinical operations and establish service-level performance baselines.
Deliverable: operation inventory and baseline metrics
Stage B — Calibrate
Develop provisional cost weights and test realistic patient-history workloads.
Deliverable: calibrated scoring model
Stage C — Shadow evaluation
Record which operations would be rejected without immediately blocking them, except where existing critical protections require enforcement.
Deliverable: false-positive and policy-impact report
Stage D — Controlled enforcement
Enable validated limits and tenant-aware resource controls with a tested rollback procedure.
Deliverable: approved enforcement configuration
Stage E — Continuous governance
Review model drift, service saturation, authorization failures, and schema changes.
Deliverable: regression results and periodic policy reviews
Rollback triggers:
* Unexpected failures in essential authorized operations.
* A significant regression in service reliability.
* Incorrect tenant isolation.
* Evidence that the policy estimator is materially undercounting resource demand.
Define operational thresholds and rollback authority before strict enforcement.
Result: ✅ Rollout plan passes; no deployment has occurred.
### 🏆 Phase 16: Final Governance Report
### A. Executive summary
The sample healthcare platform has potential risks from nested clinical records, federated service fan-out, broad historical queries, and concurrent requests. The proposed solution combines query complexity governance, bounded arguments, service-specific resource protection, and tenant-aware authorization.
### B. Schema and resolver risk map
Prioritize appointment-to-patient-to-laboratory-result paths, broad patient-history operations, and cross-service dashboard queries. Confirm actual costs through resolver and service tracing.
### C. Complexity scoring model
Use configurable field costs, cardinality multipliers, cross-service cost adjustments, and correct alias/fragment accounting. Calibrate using observed execution data.
### D. Query limit policy
Introduce bounded pagination, request-size limits, depth controls, and a calibrated complexity budget. Validate critical clinical operations before enabling new blocking policies.
### E. Resource protection architecture
Protect the gateway, scheduling database, clinical services, and shared infrastructure independently. GraphQL scoring must complement backend safeguards.
### F. Abuse and failure analysis
Test excessive historical queries, nested lists, alias expansion, retry storms, downstream timeouts, and unauthorized cross-organization access.
### G. Test and calibration plan
Use representative operations, concurrent tenant workloads, failure injection, and measured comparisons between predicted cost and actual resource consumption.
### H. Observability and cost attribution
Collect operation cost, resolver timings, downstream latency, rejection reasons, and resource usage while minimizing sensitive clinical data in logs.
### I. Implementation blueprint
Enforce validation, complexity, authorization, budgets, and deadlines at the appropriate gateway and service boundaries.
### J. Rollout roadmap
Proceed through observation, calibration, shadow evaluation, controlled enforcement, and continuous regression testing.
### K. Risk and exception register
Assign owners to authorization failures, model drift, legitimate-query rejection, service saturation, and privileged exceptions. Maintain audit trails for policy changes.
### L. Final governance verdict
### CONDITIONALLY READY — CALIBRATION REQUIRED
Verdict for this hypothetical test environment
* Strongest finding: Federated GraphQL operations can amplify work across multiple independent backend services.
* Most dangerous potential pattern: Broad nested clinical-record queries combined with concurrent downstream requests.
* First control to implement: Instrument service fan-out and enforce validated pagination and date-range bounds.
* Required pre-enforcement test: Run representative concurrent clinical queries and compare complexity predictions with measured backend work.
* Main residual risk: Service saturation or incorrect authorization despite a query passing complexity checks.
* Success conditions: Bounded query expansion, verified tenant isolation, controlled downstream concurrency, acceptable rejection rates, and compliance with agreed reliability objectives.
### 📊 Final Sample Test Scorecard
| Phase | Result |
| --------------------------------- | -------------------- |
| 1. Execution context | Conditional pass |
| 2. Schema complexity | Conditional pass |
| 3. Scoring model | Calibration required |
| 4. Query-shape controls | Design passes |
| 5. Resolver analysis | Evidence required |
| 6. Backend protection | Conditional pass |
| 7. Admission control | Design passes |
| 8. Tenant fairness | Simulation required |
| 9. Abuse resistance | Test plan passes |
| 10. Calibration testing | Awaiting execution |
| 11. Observability | Design passes |
| 12. Caching and persisted queries | Conditional pass |
| 13. Failure analysis | Risk register passes |
| 14. Implementation blueprint | Design passes |
| 15. Rollout | Plan passes |
| 16. Final report | Conditionally ready |
Overall assessment: This second sample demonstrates how the same skill can adapt its governance analysis to a federated healthcare environment, including clinical-data authorization, downstream service protection, and reliability requirements.
Testing limitation: This is a simulated skill evaluation. No actual healthcare API, production database, or GraphQL server was executed or benchmarked.
By purchasing this prompt, you agree to our terms of service
CLAUDE-5-5-SONNET
GraphQL Query Complexity Governance Engineer helps backend teams design enforceable query-cost controls based on schema structure, resolver behavior, list multipliers, and actual resource constraints.
Provide your GraphQL schema, resolver architecture, workload evidence, and resource constraints—and turn them into an actionable query-governance blueprint for protecting backend capacity.
...more
Added 1 week ago
