Math Formula Rendering Engineering: Lessons from Rewriting TeX in 10 Minutes

    This article explains why mathematical formulas are hard to render consistently across platforms and presents a practical, four-layer architecture for building a self-hosted formula rendering service. It covers parsing and whitelisting, layout and rasterization, batch rendering through session reuse, asynchronous task handling with fallback strategies, security boundaries, and quality metrics such as cache hit rate and tail latency. The goal is to turn formulas into a reliable, first-class part of cross-platform content delivery.

    Introduction: The Overlooked “Last Mile” of Content Delivery

    In technical writing and knowledge sharing, mathematical formulas sit in an awkward position. When authors write papers locally with professional typesetting tools, they can fine-tune fraction nesting, Greek letters, superscript and subscript alignment, matrix environments, and theorem numbering. But once the content moves to social platforms, chat groups, blog comments, online documents, or mobile readers, formulas often degrade into unreadable source text, or get filtered out as garbled content.

    The root cause is not the formula syntax itself, but the absence of a rendering pipeline. Mainstream rich-text formats treat plain text paragraphs as the basic unit and lack first-class support for mathematical semantics. Different clients vary widely in how they parse extended syntax. Building rendering in-house requires a whole set of engineering capabilities: fonts, a layout engine, image caching, and concurrency control. As a result, “will the formula display correctly” becomes the last-mile barrier to content distribution.

    There are roughly three traditional responses. The first is to capture images produced by typesetting software: it looks exactly as intended, but resolution is fixed, styles are inconsistent, and batch maintenance is difficult. The second is to submit source code to an online conversion service and get an image back: integration is fast, but availability, latency, and compliance risks exist. The third is to give up on formulas and keep only a text description, sacrificing precision. This article focuses on the missing middle ground between the first and second approaches and offers an engineering solution that is self-hostable, observable, and extensible.

    1. Why Math Formulas Are Inherently Hard to Render Across Platforms

    To design a sound solution, first understand the technical nature of the problem. A math formula is not ordinary text; it has three notable characteristics.

    First, two-dimensional layout semantics. Ordinary text is a linear stream, while a formula is a two-dimensional structure: the numerator sits above the denominator, superscripts and subscripts are offset from the baseline, the coverage of a radical changes with content height, and matrices align by rows and columns. Expressing a two-dimensional structure with linear characters inevitably introduces ambiguity.

    Second, strong dependence on font metrics. Rendering quality depends heavily on the glyph design and metrics of math fonts, including glyph width, height, italic correction, and superscript/subscript scaling ratios. Without the matching fonts, the engine can only fall back to approximate layout, producing abnormal spacing, misaligned symbols, and jittery line spacing.

    Third, context sensitivity. The same snippet differs between display math and inline math in font size, fraction compression strategy, and the placement of integral limits. Whether it is inside a matrix environment or nested within another fraction also changes the final layout. This means rendering cannot be a simple string replacement; it must build a syntax tree and lay out recursively according to context.

    These three points turn “convert a formula into an image” into an engineering task that needs a complete rendering engine, not a one-off text transformation.

    2. Lessons from Classic Typesetting Systems: Precision, Programmability, and Engineering Cost

    The de facto standard for modern math typesetting originated from an academic project started in the late 1970s. Its author, dismayed by a sharp drop in print quality when a monograph was reprinted, decided to build his own typesetting engine. He originally planned to finish in a few months and ended up spending nearly a decade. The system is known for extremely high typesetting precision; its version number increases by converging digit by digit toward pi, and the author long offered small cash rewards for reported defects, with most recipients choosing to frame and keep the checks rather than cash them. This history is widely told in developer communities and forms the narrative backdrop for “rewriting it in ten minutes” discussions.

    From an engineering perspective, two things are worth borrowing.

    First, typesetting is modeled as a box-glue-penalty optimization problem. Characters are treated as boxes, the gaps between boxes as glue with stretchability, and line breaking and alignment are quantified as the minimization of a penalty function. This abstraction makes complex typesetting computable and is the fundamental reason its quality stays stable.

    Second, it is essentially a Turing-complete language. Macro expansion, conditionals, loops, and recursion provide full programming capability, so the community has built fractal drawing, maze solving, and cellular automaton simulations inside the typesetting language itself. This programmability brings remarkable expressive power, along with well-known engineering costs: macro expansion is order-sensitive, error messages are cryptic, compile time is unpredictable, and results are hard to analyze statically. The widely repeated “steep learning curve” is essentially the tension between general-purpose language features and domain-specific needs.

    So if you want to reimplement similar capability in a modern systems language, the rational approach is not to replicate every general-purpose programming feature, but to keep the determinism of the typesetting core and strip away unnecessary metaprogramming complexity. This is also why many teams now adopt a “mature rendering engine plus a self-built service layer” combination: leave the hardest typesetting details to components validated over the long term, and keep engineering control in your own hands.

    3. Solution Design: A Four-Layer Architecture from Source to Image

    A production-ready formula rendering service can be divided into four layers.

    3.1 Ingress Layer

    This layer receives formula content, which can be a single formula, an array of formulas, or an entire document. It performs four tasks: request validation (length limits, character set, environment whitelist), identity and quota recognition, sync/async routing, and cache key generation.

    Cache key design directly affects hit rate. It is recommended to hash the normalized source together with rendering parameters (scale, color depth, transparent background, font theme) and output specifications, so the same formula is not recomputed because of differences in how parameters are written:

    1. cache_key = hash(normalize(latex) + render_params + output_spec)

    Here normalize should at least unify whitespace, macro aliases, and common equivalent forms, for example folding different kinds of spaces and line breaks into a consistent representation.

    3.2 Parsing Layer

    Preprocess the input with whitelisting. Production must assume input comes from untrusted sources, so capabilities such as file read/write, external resource inclusion, and arbitrary command execution should be explicitly disabled, keeping only the macro set needed for math typesetting. This step is both a security boundary and a stability boundary.

    After preprocessing, build a structure tree that identifies block-level constructs such as inline math, display math, matrix environments, and alignment environments, providing the basis for batch and segmented rendering.

    3.3 Rendering and Rasterization Layer

    This is the core of quality. The rendering flow includes layout computation, glyph selection, ligatures and kerning, baseline alignment, and line spacing calculation, producing a vector description that is then rasterized into a bitmap.

    Key engineering parameters include the base font size to pixel density ratio, the font fallback chain, the line spacing compensation factor, superscript/subscript scaling ratios, and long-fraction line-breaking strategy. If device-independent units (such as 1/100 mm) are used as the intermediate representation, the final rasterization can scale uniformly to the target resolution, letting one layout serve web, print, and high-resolution screens.

    3.4 Output and Distribution Layer

    This layer handles encoding, compression, object storage, and origin fetch. Formula images are numerous and updated frequently, so content-addressed storage keys are recommended, combined with edge caching and long expiration policies, so each formula is computed only once globally.

    4. Key Technology Choices and Engineering Practices

    4.1 Rendering Engine: Build or Reuse

    If you care about typesetting detail and ecosystem compatibility, reusing a typesetting engine validated over the long term is the safer choice. If you care about low latency and memory safety for a single render, you can implement a lightweight service layer in a systems programming language, leaving layout to mature components and keeping concurrency scheduling, caching, and monitoring in your own code. The two are not in conflict; they are the mainstream layered practice today.

    One common misconception needs clarification: rewriting core components in a systems programming language pays off in runtime characteristics and deployment form, not in automatically better typesetting quality. Typesetting quality depends on fonts, metrics data, and algorithm implementation, not on the implementation language. Treating a rewrite as “switch the language and it looks better” is a typical technical misjudgment.

    4.2 Batch Rendering and Task Merging

    When a single request renders an entire document, repeatedly starting the engine adds significant fixed overhead. A better approach is to reuse the same engine instance within one session, process multiple formula snippets in order, and reclaim resources when the session ends:

    1. batch = session.create(extracted_formulas)
    2. results = batch.render_all(scale=3, dpi=300, transparent=true)
    3. batch.close()

    This “session reuse” pattern reduces fixed overhead from “once per formula” to “once per request,” which pays off clearly for long documents.

    4.3 Asynchrony and Fallback Strategy

    Rendering long documents or complex formulas can take a while, and synchronous APIs easily trigger gateway timeouts. It is advisable to design two paths: lightweight requests return synchronously; heavy requests enter a message queue and return a task identifier, with the client polling or subscribing to a callback for the result. Also prepare a fallback chain: return a vector format first, then a low-resolution placeholder marked “rendering,” and finally the structured source text, so content is always readable.

    4.4 Security Boundaries

    A math typesetting engine is naturally a component that “executes untrusted descriptions,” so security design must come first:

    • Disable file system and network access;
    • Limit memory and execution time, and force termination when exceeded;
    • Set hard limits on input length, nesting depth, and macro expansion levels;
    • Isolate the rendering process from the main service process, running in a container with a read-only file system and least privilege;
    • Validate types and enforce size limits on uploaded fonts and resources.

    5. Quality and Performance Evaluation

    Once the solution is in place, build a quantifiable evaluation system instead of relying on subjective “looks fine” judgments.

    Correctness metrics: Build a regression suite covering typical structures such as nested fractions, radicals, matrices, alignment environments, and special symbols, using pixel-difference comparison to detect rendering offsets.

    Performance metrics: Measure cold-start latency, average per-formula latency within a session, batch throughput, and cache hit rate separately. Cache hit rate is recommended as a core observation item, because it reflects both ingress-layer design quality and overall cost.

    Stability metrics: Track rendering failure rate, timeout rate, and number of fallback triggers. A sudden spike in fallbacks usually signals a shift in input distribution or a resource bottleneck and should trigger an alert.

    Observability: For each render, record the digest of the normalized source (not the plaintext, to avoid leaking sensitive content), latency breakdown, engine version, font version, and output specification, making it easy to reproduce issues and roll back versions.

    6. Typical Use Cases

    • Technical communities and knowledge bases: Authors write in a unified syntax; the platform batch-generates and caches images at publish time, so comments and mobile reading are unaffected by client capability differences.
    • Online education: Formulas in a question bank are cached per question, and lecture notes and exercises share the same rendering service for consistent style.
    • Internal documents and reports: The build pipeline pre-renders all formulas when generating the site, and the static assets ship with the site, avoiding runtime dependence on external services.
    • AI question answering and automated summarization: Structured formula content produced by a model is turned into images by the rendering service and embedded in replies, balancing precision and display compatibility.
    • Content moderation up front: Complete source whitelisting before image generation, preventing the rendering layer from being used to execute unintended descriptions.

    7. Common Pitfalls

    Pitfall 1: Believing a different implementation language improves typesetting quality. Quality is determined by algorithms and font metrics; the language only affects runtime behavior.

    Pitfall 2: Exposing every capability to users. A general-purpose programmable typesetting description is often a burden in a real service; a whitelisted subset is the operable choice.

    Pitfall 3: Ignoring cache key design. A crude key design causes recomputation and cache pollution, directly amplifying cost.

    Pitfall 4: Measuring only the average and not the tail. Tail latency in batch rendering of long documents determines the user experience, so percentile metrics should be primary.

    Pitfall 5: Carrying all traffic on a synchronous API. Without an asynchronous path, traffic peaks can cause an avalanche.

    Conclusion

    Around the discussion of “rewriting a classic typesetting system in ten minutes,” what developers should really care about is not the time figure, but the engineering reality it reveals: math formula rendering is a long pipeline made up of parsing, font metrics, layout algorithms, rasterization, and cache distribution, and no single-point replacement can substitute for the overall design. The sensible path is to reuse a typesetting core validated over the long term, build a service layer on top of it with whitelisted security, asynchronous tasks, layered caching, and full-pipeline observability, and continuously guard quality with a regression suite and percentile metrics. Once this pipeline is engineered and consolidated, formulas can become a stable first-class citizen in cross-platform content delivery, just like images and code blocks.