How Mermaid’s maxTextSize and maxEdges Configuration Settings Prevent Resource Exhaustion from Malicious Diagrams

Mermaid’s maxTextSize and maxEdges configuration settings act as hard resource quotas that abort parsing when input exceeds 50,000 characters or 500 edges, preventing denial-of-service attacks from maliciously large diagram definitions.

The mermaid-js/mermaid library transforms textual diagram definitions into visual flowcharts, sequence diagrams, and other graph types. Because the parsing and layout algorithms consume significant CPU and memory, attackers could exploit unbounded input to trigger browser freezes or server crashes. The maxTextSize and maxEdges configuration settings provide immutable boundaries that terminate processing before dangerous resource thresholds are reached.

Understanding Resource Exhaustion Risks in Diagram Rendering

Memory and Parsing Time Abuse

Attackers can submit extremely long input strings containing hundreds of thousands of characters. Without limits, the parser allocates massive buffers to process these strings, causing memory spikes in server environments or tab crashes in browsers.

CPU and Layout Computation Abuse

Graph layout algorithms perform combinatorial work proportional to edge count. Thousands of edges force the layout engine (ELK, Dagre, etc.) to consume excessive CPU cycles, potentially hanging the process or triggering out-of-memory errors during coordinate calculation.

How maxTextSize Limits Memory Consumption

The maxTextSize setting defines the maximum character count the parser will process. The default value is 50,000 characters, configurable via mermaid.initialize({ maxTextSize: ... }).

In packages/mermaid/src/mermaidAPI.ts, the rendering pipeline validates input length before instantiating any diagram:

// packages/mermaid/src/mermaidAPI.ts#L18-L22
if (text.length > config.maxTextSize) {
  // Return placeholder message instead of parsing
  return MAX_TEXTLENGTH_EXCEEDED_MSG;
}

When input exceeds the limit, the API returns the MAX_TEXTLENGTH_EXCEEDED_MSG placeholder, aborting further parsing and preventing buffer allocation attacks.

How maxEdges Constrains Computational Complexity

The maxEdges setting caps the number of relationships in flowcharts, preventing layout algorithm overload. The default limit is 500 edges.

In packages/mermaid/src/diagrams/flowchart/flowDb.ts, the addSingleLink method enforces this boundary:

// packages/mermaid/src/diagrams/flowchart/flowDb.ts#L94-L101
addSingleLink(id1: string, id2: string, ...): void {
  if (this.edges.length >= (this.config.maxEdges ?? 500)) {
    throw new Error(
      `Edge limit exceeded. ${this.edges.length} edges found, but the limit is ${this.config.maxEdges ?? 500}.`
    );
  }
  // ... proceed to add edge
}

When the edge count reaches the threshold, the engine throws an error immediately, halting diagram construction before the layout engine processes an unsafe graph.

Security Configuration and Override Protection

Both settings reside in the secure configuration block, ensuring diagram definitions cannot override them. In packages/mermaid/src/config.type.ts, these fields are defined as configurable only programmatically:

// packages/mermaid/src/config.type.ts#L83-L90
export interface MermaidConfig {
  maxTextSize?: number;
  maxEdges?: number;
  // ...
  secure?: Array<keyof MermaidConfig>; // Keys listed here cannot be set in diagram text
}

By including maxTextSize and maxEdges in the secure array during initialization, sites ensure that even if an attacker controls the diagram text, they cannot lift the resource quotas.

Practical Implementation Examples

Tightening Security for Untrusted Input

For applications rendering user-generated diagrams, reduce defaults to minimize attack surface:

mermaid.initialize({
  maxTextSize: 10_000,    // 10 KB limit
  maxEdges: 200,          // Strict edge limit
  securityLevel: 'strict' // Prevent diagram-level config overrides
});

Raising Limits for Trusted Environments

Server-side batch processing of known-safe diagrams can increase quotas:

mermaid.initialize({
  maxTextSize: 200_000,   // 200 KB for large documentation diagrams
  maxEdges: 2_000,        // Complex architecture diagrams
  securityLevel: 'loose'  // Allow in-diagram config (use with caution)
});

Testing the Safeguards

Verify your configuration blocks oversized diagrams:

// Jest test example
test('throws when exceeding maxEdges', async () => {
  mermaid.initialize({ maxEdges: 1 });
  const diagram = `
    graph TD
    A --> B
    B --> C
  `;
  await expect(mermaid.render('id1', diagram)).rejects.toThrow(
    /Edge limit exceeded/
  );
});

Summary

  • maxTextSize (default 50,000 characters) prevents memory exhaustion by rejecting oversized input strings before parsing begins, as enforced in packages/mermaid/src/mermaidAPI.ts.
  • maxEdges (default 500) prevents CPU exhaustion by capping graph complexity before layout algorithms execute, enforced in packages/mermaid/src/diagrams/flowchart/flowDb.ts.
  • Both settings are part of the secure configuration block, meaning they can only be set programmatically and cannot be overridden by malicious diagram definitions.
  • These resource quotas protect both client-side browsers and server-side rendering processes from denial-of-service attacks via maliciously crafted diagram definitions.

Frequently Asked Questions

What happens when a diagram exceeds the maxTextSize limit?

When input exceeds the configured maxTextSize, Mermaid aborts parsing and returns a placeholder message reading "Maximum text size in diagram exceeded." This prevents the parser from allocating buffers for oversized strings, protecting against memory exhaustion attacks in both browser and Node.js environments.

Can attackers override maxTextSize or maxEdges by embedding configuration in the diagram text?

No. When these settings are included in the secure configuration array during initialization, they cannot be modified via diagram definitions. Only programmatic configuration through mermaid.initialize() can change these values, ensuring malicious diagram code cannot lift resource protections to exhaust system resources.

Does the maxEdges limit apply to all diagram types or only flowcharts?

The maxEdges setting primarily applies to flowcharts and similar graph-based diagrams that use the FlowDb class. The enforcement occurs in packages/mermaid/src/diagrams/flowchart/flowDb.ts within the addSingleLink method. Other diagram types like sequence diagrams or pie charts may have different internal limits or validation mechanisms specific to their rendering engines.

For applications rendering untrusted user-generated diagrams, set maxTextSize to 10,000 characters or lower and maxEdges to 200 or fewer. For trusted internal documentation with complex architecture diagrams, you may raise maxTextSize to 200,000 and maxEdges to 2,000, provided you validate inputs through other means. Always pair these settings with securityLevel: 'strict' to prevent configuration injection attacks.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →