Inferensys

Prompt

Service Dependency Graph Coupling Score Prompt

A practical prompt playbook for platform engineers and architects who need to quantify coupling risk in a service dependency graph before making extraction, merge, or refactoring decisions.
Risk analyst performing AI risk assessment on laptop, risk matrices visible, casual office risk session.
PROMPT PLAYBOOK

When to Use This Prompt

Quantify coupling risk in a service dependency graph before planning a migration, extraction, or architectural refactor.

Use this prompt when you have a known service dependency graph—represented as a list of nodes and directed edges—and need a quantitative coupling analysis to inform architectural decisions. The ideal user is a platform engineer, architect, or technical lead preparing for a monolith extraction, microservice consolidation, or dependency modernization effort. You must already have the dependency graph available, typically derived from service meshes, API gateways, static analysis tools, or architecture documentation. The prompt computes afferent coupling (Ca), efferent coupling (Ce), instability (I = Ce / (Ca + Ce)), and ranks services by change propagation risk. It also detects cyclic dependencies and flags services that exceed configurable coupling thresholds.

This is a design-level analysis prompt, not a runtime observability tool. It assumes the dependency graph is accurate and complete at the time of analysis. The output includes a ranked risk table, cyclic dependency detection, and threshold alerts that can feed directly into an architecture decision record or migration sequencing plan. You can configure the instability threshold, maximum acceptable cycle length, and the minimum dependency count that triggers a warning. The prompt works best when paired with a structured input format—typically JSON or YAML representing nodes, edges, and optional metadata like protocol type or criticality labels. For high-stakes refactoring decisions, always validate the output against your own architecture knowledge and consider a human architecture review before acting on the rankings.

Do not use this prompt when you need real-time traffic analysis, runtime latency data, infrastructure-level network topology, or dynamic dependency discovery. It is not a substitute for a full architecture review—it quantifies coupling, not correctness, and cannot assess whether a dependency is semantically appropriate. If your dependency graph is incomplete or inferred from unreliable sources, the coupling scores will be misleading. For systems with asynchronous, event-driven dependencies, ensure those indirect couplings are represented as edges in the input graph, or the analysis will miss hidden propagation paths. After running this analysis, the natural next step is to feed the ranked risk list into a service extraction candidate scoring prompt or a change propagation risk analysis prompt to build a sequenced migration plan.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Service Dependency Graph Coupling Score Prompt delivers value and where it introduces risk. Use this to decide if the prompt fits your current architecture review workflow.

01

Good Fit: Pre-Migration Risk Assessment

Use when: You are planning a monolith decomposition or service extraction and need to quantify which services carry the highest change propagation risk. Why it works: The prompt produces ranked coupling scores and instability metrics that directly inform extraction sequencing.

02

Good Fit: Architecture Review Gate

Use when: You require a standardized coupling analysis as part of an Architecture Decision Record or design review gate. Why it works: The structured output with afferent/efferent coupling scores and cyclic dependency alerts provides reproducible evidence for review decisions.

03

Bad Fit: Runtime Dependency Discovery

Avoid when: You need to discover actual runtime dependencies from live traffic or distributed traces. Why it fails: This prompt analyzes a provided static graph. It cannot observe runtime call patterns, latent dependencies, or dynamic routing behavior that static analysis misses.

04

Bad Fit: Single-Service Deep Dive

Avoid when: You need a detailed internal analysis of one service's code quality, database schema, or business logic. Why it fails: The prompt operates at the graph topology level. It scores coupling risk across the system but does not evaluate internal implementation quality or domain correctness.

05

Required Input: Dependency Graph Structure

What you must provide: A complete service dependency graph with nodes, directed edges, and edge types. Guardrail: Validate that the graph includes all production services and their call relationships before running the prompt. Missing edges produce falsely low coupling scores and hide change propagation paths.

06

Operational Risk: Stale Graph Data

What to watch: Dependency graphs drift as teams add services, change call patterns, or introduce asynchronous communication. Guardrail: Timestamp the graph input and reject analyses based on graphs older than your team's agreed freshness window. Pair this prompt with automated dependency discovery tooling for production use.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt that quantifies coupling risk across a service dependency graph, producing scored instability metrics and ranked change propagation risks.

This prompt template is designed to be pasted directly into your AI workflow. It accepts a structured representation of your service dependency graph and returns a quantitative coupling analysis. The template uses square-bracket placeholders that you must replace with your actual data before sending. The output includes afferent/efferent coupling scores, instability metrics, and a prioritized list of services that pose the highest change propagation risk. This is not a conversational prompt—it expects structured input and returns structured output suitable for parsing into dashboards, architecture decision records, or CI/CD fitness functions.

text
You are a platform architecture analyst evaluating a service dependency graph for coupling risk. Your task is to compute coupling scores, instability metrics, and change propagation risk rankings from the provided graph.

## INPUT
[DEPENDENCY_GRAPH]

## DEFINITIONS
- **Afferent Coupling (Ca):** Number of services that depend on this service (incoming dependencies).
- **Efferent Coupling (Ce):** Number of services this service depends on (outgoing dependencies).
- **Instability (I):** I = Ce / (Ca + Ce). Range 0.0 (stable, many dependents) to 1.0 (unstable, depends on many others).
- **Cyclic Dependency:** A path where a service transitively depends on itself (A→B→C→A).

## OUTPUT_SCHEMA
Return a JSON object with the following structure:
{
  "services": [
    {
      "name": "string",
      "afferent_coupling": number,
      "efferent_coupling": number,
      "instability": number,
      "dependents": ["string"],
      "dependencies": ["string"],
      "cyclic_dependency_risk": "none" | "direct" | "transitive",
      "change_propagation_risk": "low" | "medium" | "high" | "critical"
    }
  ],
  "cycles_detected": [
    {
      "cycle": ["string"],
      "severity": "warning" | "critical"
    }
  ],
  "ranked_by_risk": ["string"],
  "summary": {
    "total_services": number,
    "average_instability": number,
    "cyclic_dependency_count": number,
    "highest_risk_service": "string"
  }
}

## CONSTRAINTS
- Compute Ca and Ce from the provided graph only. Do not infer dependencies not present.
- Instability must be calculated as Ce / (Ca + Ce). If Ca + Ce = 0, set instability to 0.0 and flag the service as isolated.
- Change propagation risk is derived from: instability score, number of dependents, and presence of cyclic dependencies. Use this mapping:
  - Critical: instability > 0.8 AND dependents > 3, OR part of a critical cycle.
  - High: instability > 0.7 OR part of a warning cycle.
  - Medium: instability between 0.3 and 0.7.
  - Low: instability < 0.3.
- Detect both direct cycles (A→B→A) and transitive cycles (A→B→C→A).
- Rank services by change propagation risk (critical first, then high, medium, low).
- If the input is malformed or missing dependency information, return an error object: {"error": "string", "detail": "string"}.

## EXAMPLE_INPUT_FORMAT
The [DEPENDENCY_GRAPH] will be provided as a JSON adjacency list:
{
  "service-a": ["service-b", "service-c"],
  "service-b": ["service-c"],
  "service-c": ["service-a"],
  "service-d": []
}

## RISK_LEVEL
This analysis informs architectural decisions about service decomposition, migration sequencing, and integration testing scope. Outputs should be reviewed by a senior engineer or architect before driving refactoring priorities. Cyclic dependencies flagged as critical require immediate attention.

To adapt this prompt for your environment, replace [DEPENDENCY_GRAPH] with your actual service dependency data in the adjacency list format shown in the example. If your graph is large, consider batching or pre-filtering to services within a single bounded context to keep the analysis focused. The output schema is designed to be machine-readable—pipe the JSON directly into your architecture dashboard, CI/CD fitness function, or ADR generation workflow. For high-stakes decisions, always pair this automated analysis with human architectural review, especially when the output recommends restructuring services with high afferent coupling.

IMPLEMENTATION TABLE

Prompt Variables

Each placeholder required by the Service Dependency Graph Coupling Score Prompt. Replace these with concrete values before sending the prompt. Validation notes describe how to check that the input is well-formed and safe.

PlaceholderPurposeExampleValidation Notes

[DEPENDENCY_GRAPH]

The service dependency graph to analyze, represented as a list of directed edges between services.

ServiceA -> ServiceB ServiceB -> ServiceC ServiceA -> ServiceC

Parse check: each line must match the pattern 'source -> target'. Reject empty graphs. Null not allowed.

[GRAPH_FORMAT]

Specifies the serialization format of the dependency graph input.

edge-list

Enum check: must be one of 'edge-list', 'adjacency-list', or 'mermaid'. Default to 'edge-list' if omitted.

[SERVICE_NAMES]

An optional list of service names to scope the analysis. If omitted, all services in the graph are analyzed.

ServiceA, ServiceB, ServiceC

Parse check: comma-separated list. Each name must appear in the dependency graph. Null allowed to indicate full graph analysis.

[COUPLING_THRESHOLDS]

Threshold values for flagging high coupling. Defines warning and critical levels for afferent and efferent coupling.

afferent_warning: 5 afferent_critical: 10 efferent_warning: 5 efferent_critical: 10

Schema check: must be a map with integer values for each threshold key. Values must be positive integers. Null allowed to use defaults.

[INSTABILITY_THRESHOLDS]

Threshold values for flagging instability metrics. Defines the acceptable range for a service's instability score (0.0 to 1.0).

min_stable: 0.3 max_stable: 0.7

Schema check: must be a map with float values between 0.0 and 1.0. min_stable must be less than max_stable. Null allowed to use defaults.

[OUTPUT_FORMAT]

The desired output format for the analysis results.

json

Enum check: must be one of 'json', 'markdown', or 'csv'. Default to 'json' if omitted.

[INCLUDE_VISUALIZATION]

Flag indicating whether to include a Mermaid.js diagram of the dependency graph in the output.

Boolean check: must be 'true' or 'false'. Default to 'false' if omitted.

[CYCLE_DETECTION_MODE]

Specifies the algorithm or strictness for cycle detection.

strict

Enum check: must be 'strict' (all cycles) or 'simple' (only direct cycles). Default to 'strict' if omitted.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Service Dependency Graph Coupling Score Prompt into a reliable CI pipeline with validation, retries, logging, and human review gates.

This prompt is designed to be called from a script or CI pipeline that extracts a dependency graph from service mesh data, API gateway configurations, or static analysis tools. The harness should treat the prompt as a pure reasoning step over structured input—no tool use, retrieval, or external API calls are required. The model receives a validated directed graph and returns a JSON risk assessment that downstream systems can consume for visualization, alerting, or architecture review workflows.

Before sending the graph to the model, validate the input structure: every edge target must exist in the node list, and the graph must be a valid directed graph with no dangling references. Reject malformed graphs before they reach the model. After receiving the model output, validate the JSON against the output contract—check that afferent_coupling, efferent_coupling, and instability fields are present for every service, that scores are numeric and within expected ranges, and that the ranked_services array is sorted by risk score descending. If validation fails, retry once with the validation errors appended to the prompt as [CONSTRAINTS]. Do not retry more than once without human intervention; repeated failures indicate a structural problem with the input graph or the prompt itself.

Log every invocation with the graph hash, model version, timestamp, and raw output for auditability. This is especially important when the prompt is used to inform architecture decisions that affect team structures or migration sequencing. For high-stakes architecture decisions—such as identifying services for extraction or merge—route the output to a human reviewer before acting on the ranked risk list. The reviewer should confirm that the coupling scores align with their operational knowledge of the system and that no counterintuitive rankings result from incomplete dependency data. The prompt does not replace architectural judgment; it accelerates the analysis that informs it.

Model choice matters here. The prompt requires reasoning over graph structure and numeric scoring, which most frontier models handle well. However, smaller or older models may produce malformed JSON or inconsistent scores. If you observe frequent validation failures, consider upgrading the model or adding a second validation pass with a different model as a cross-check. The prompt template includes [CONSTRAINTS] as a placeholder for injecting validation feedback on retry, and [RISK_LEVEL] to adjust the sensitivity of cyclic dependency detection and instability thresholds based on your team's tolerance for coupling risk.

IMPLEMENTATION TABLE

Expected Output Contract

The model must return a JSON object matching this schema. Validate programmatically before consuming the output. Each field has a concrete validation rule that can be enforced in application code.

Field or ElementType or FormatRequiredValidation Rule

services

Array of objects

Array length >= 1. Each element must have id, name, afferent_coupling, efferent_coupling, instability, and change_risk_score fields.

services[].id

String

Non-empty string matching the service identifier from the input dependency graph. Must be unique within the array.

services[].name

String

Non-empty string. Should match the human-readable name from the input. No length constraint beyond non-empty.

services[].afferent_coupling

Integer

Integer >= 0. Count of inbound dependencies from other services in the graph. Validate against input graph for correctness.

services[].efferent_coupling

Integer

Integer >= 0. Count of outbound dependencies to other services in the graph. Validate against input graph for correctness.

services[].instability

Float

Float between 0.0 and 1.0 inclusive. Computed as efferent / (afferent + efferent). If both are 0, instability must be 0.0. Validate formula.

services[].change_risk_score

Float

Float between 0.0 and 1.0 inclusive. Higher values indicate greater change propagation risk. Must be monotonically related to efferent_coupling and instability.

cyclic_dependencies

Array of arrays

Each element is an array of 2+ service IDs forming a cycle. Empty array if no cycles detected. Validate each cycle exists in the input graph.

cyclic_dependencies[].severity

String

One of: low, medium, high, critical. Severity must increase with cycle length and number of services affected.

threshold_alerts

Array of objects

Each object has service_id, metric, value, threshold, and alert_level fields. Generate for any service exceeding coupling or instability thresholds.

threshold_alerts[].alert_level

String

One of: warning, critical. warning for threshold breaches below 20% over limit. critical for breaches at or above 20% over limit.

ranked_services

Array of objects

Array of {service_id, rank, change_risk_score} sorted by change_risk_score descending. rank starts at 1. No ties in rank; break ties by efferent_coupling descending.

visualization_data

Object

If present, must contain nodes (array of {id, label, group}) and edges (array of {from, to, weight}). Null allowed. Validate node ids match services array.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using the Service Dependency Graph Coupling Score Prompt and how to guard against it.

01

Hallucinated Dependency Edges

What to watch: The model invents service-to-service calls that do not exist in the provided graph, inflating coupling scores and creating false change propagation paths. This is common when the input graph is sparse or the model attempts to fill perceived gaps based on naming conventions. Guardrail: Require the prompt to cite specific edges from the input graph for every coupling claim. Add a post-processing validation step that diffs the output edges against the input adjacency list and flags any edge not present in the source data.

02

Instability Metric Miscalculation

What to watch: The model produces afferent (Ca) and efferent (Ce) coupling counts that do not sum correctly, leading to incorrect instability scores (I = Ce / (Ca + Ce)). This often occurs when the graph is large and the model loses count mid-reasoning. Guardrail: Include the exact formula in the prompt constraints and require the model to output raw Ca and Ce counts alongside the computed I score. Implement a deterministic post-processing script that recalculates I from the extracted counts and rejects outputs where the math does not check out.

03

Cyclic Dependency Blind Spots

What to watch: The model fails to detect cycles longer than 2-3 nodes, especially in large graphs where the cycle spans multiple services with indirect dependencies. This produces a false sense of architectural safety. Guardrail: Never rely solely on the model for cycle detection. Run a deterministic graph algorithm (e.g., Tarjan's or Johnson's) on the same input data to identify all cycles. Use the prompt output only for explaining the impact of cycles already detected algorithmically.

04

Ranking Instability Across Runs

What to watch: The ranked list of services by change propagation risk shifts significantly between runs with identical input, undermining trust in the prioritization. This is caused by non-deterministic sampling when the model weighs multiple risk factors. Guardrail: Set the temperature to 0 for this prompt. Run the prompt three times and use only services that appear consistently in the top N across all runs. If ranking variance exceeds a threshold, flag the output for human review before using it to prioritize extraction work.

05

Threshold Alert False Positives

What to watch: The model flags benign dependencies as high-risk because it misinterprets the coupling threshold or applies a blanket rule without considering the domain context of the relationship. Guardrail: Include explicit threshold definitions in the prompt with domain-aware exception criteria. Require the model to provide a one-sentence justification for every threshold violation it reports, citing the specific metric value and why it crosses the boundary.

06

Visualization-Ready Output Format Drift

What to watch: The JSON structure for visualization-ready output (e.g., nodes and edges arrays for D3 or Graphviz) drifts in field names, types, or nesting across runs, breaking downstream rendering pipelines. Guardrail: Provide a strict JSON Schema for the visualization output block in the prompt. Validate the output against the schema before passing it to the visualization layer. Reject and retry any output that fails schema validation, with the validation error message fed back into the retry prompt.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Service Dependency Graph Coupling Score Prompt before integrating it into a production architecture review workflow. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Afferent Coupling (Ca) Accuracy

Ca score for each service matches manual count of incoming dependencies from the provided graph within ±1

Ca score deviates by >1 for any service; missing or phantom incoming edges

Parse output JSON. For each service, count incoming edges in the input graph. Assert |output.Ca - manual_count| ≤ 1 for all services.

Efferent Coupling (Ce) Accuracy

Ce score for each service matches manual count of outgoing dependencies from the provided graph within ±1

Ce score deviates by >1 for any service; missing or phantom outgoing edges

Parse output JSON. For each service, count outgoing edges in the input graph. Assert |output.Ce - manual_count| ≤ 1 for all services.

Instability Metric Calculation

Instability (I) = Ce / (Ca + Ce) computed correctly for every service, with division-by-zero handled as I=0 when Ca+Ce=0

Incorrect I value for any service; NaN, null, or missing I when Ca+Ce=0

Parse output JSON. For each service, compute expected I = Ce / (Ca + Ce) with 0 denominator → 0. Assert |output.I - expected_I| < 0.01 for all services.

Cyclic Dependency Detection

All cycles present in the input graph are reported with participating services listed; no false positive cycles

Missed cycle in graph known to contain cycles; reported cycle that does not exist in input graph

Use a test graph with known cycles (e.g., A→B→C→A). Assert output.cyclic_dependencies contains exactly the expected cycle sets. Use a cycle-free graph and assert output.cyclic_dependencies is empty.

Ranked Service List Completeness

Every service in the input graph appears exactly once in the ranked list, sorted by change propagation risk descending

Missing services, duplicate entries, or incorrect sort order

Parse output.ranked_services. Assert length equals unique service count in input graph. Assert list is sorted by risk_score descending. Assert no duplicate service names.

Threshold Alert Triggering

Alerts fire when coupling scores exceed configured thresholds; no alerts when all scores are below thresholds

Alert missing when Ca > [CA_THRESHOLD] or Ce > [CE_THRESHOLD]; alert present when all scores are below thresholds

Provide a graph where one service has Ca=12 with [CA_THRESHOLD]=10. Assert output.alerts contains an entry for that service. Provide a graph where all Ca ≤ 10 and all Ce ≤ 10. Assert output.alerts is empty.

Output Schema Conformance

Output is valid JSON matching the [OUTPUT_SCHEMA] exactly: all required fields present, correct types, no extra top-level keys

Missing required field; wrong type (e.g., string instead of number); extra unexpected fields

Validate output against [OUTPUT_SCHEMA] using a JSON schema validator. Assert validation passes with no errors. Check field types: Ca, Ce, I, risk_score must be numbers; service names must be strings; cyclic_dependencies must be array of arrays.

Visualization-Ready Output Structure

Output includes a graph_data section with nodes and edges arrays suitable for direct rendering in a graph visualization library

graph_data missing, nodes array missing service names, edges array missing source-target pairs, or format incompatible with common libraries

Parse output.graph_data. Assert nodes is array of objects with id field matching service names. Assert edges is array of objects with source and target fields matching node ids. Verify node and edge counts match input graph.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet) and a manually curated dependency graph in JSON or DOT format. Drop the strict schema validation and focus on getting a readable coupling score table and a ranked risk list. Accept raw markdown output.

Simplify the prompt by removing the [OUTPUT_SCHEMA] block and replacing it with: Return a markdown table with columns: Service, Afferent Coupling, Efferent Coupling, Instability, Risk Score, and a ranked list of services by change propagation risk.

Watch for

  • Missing cyclic dependency detection when the graph is large
  • Hallucinated service names not present in the input graph
  • Inconsistent instability calculations across multiple runs
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.