Skip to content

Contact

Mexico City, Mexico
Available for remote and on-site projects.

Professional networks

LinkedIn · GitHub · Email
Applied engineering, measurable results.

Production-Grade OCR+LLM Pipelines

· 15 min read · Samuel Torres

A production-grade OCR+LLM pipeline separates three jobs: OCR reads the pixels, the LLM turns messy text into structured fields, and plain code decides. I ran that split behind a promotion that managed a fixed pool of 80,000 folios, verifying purchase receipts with Tesseract and LLaMA 3.3 70B, unattended, every 2 minutes.

In production, reading the image and asking the model is the easy part. The hard part is everything around it: preparing the image, forcing the model to answer in a predictable format, deciding what to do when it is unsure, keeping two processes from taking the same job, and knowing whether the system is still healthy. This guide follows that thread, from the receipt to the assigned folio. The code is illustrative: it shows the pattern, not the client's code, and table names and paths are made up.

Architecture: OCR reads, the LLM structures, code decides

OCR+LLM pipeline: a document flow where OCR extracts text, an LLM structures it, and deterministic rules approve or reject it.

The order matters more than the models. OCR is cheap and dumb. The LLM is smart and non-deterministic. Rules are boring and auditable. Each one does only what it is good at.

The paper Operationalizing Document AI (arXiv:2605.18818) splits the system into microservices on Kubernetes, with queues distributing the work. Two of its findings match what I saw on a much smaller system:

  • OCR, not the language model, dominated end-to-end latency in their batch profiling.
  • Concurrency was capped by shared inference capacity, not by the number of workers.

The consequence: scale OCR and inference separately, and put a queue between them. This is the worker, simplified, that runs for each document:

def process(job):
    # Idempotency: the job key is the receipt hash, so a retry after a crash
    # never creates a second verdict for the same image.
    if verdicts.exists(job.sha256):
        return
    text = pytesseract.image_to_string(preprocess(job.image), lang="spa")
    # The model only proposes structured fields. It never approves anything.
    fields = llm.extract(text, schema=RECEIPT_SCHEMA, temperature=0)
    # Business rules live in code: testable, versioned, auditable.
    ok, reason = rules.validate(fields, promo=job.promo)
    status = "approved" if ok else ("review" if reason.uncertain else "rejected")
    verdicts.save(job.sha256, status, reason, fields)

Three states, not two. "Review" is the release valve: anything the rules can't settle goes to a human instead of being guessed.

The case: an 80,000-folio pool with no manual review

For Panini Fan Zone FWC 2026, built as part of the Conqr Digital Agency team, I wrote two custom WordPress plugins in PHP, on MySQL. They issued and tracked a fixed pool of 80,000 folios (unique entry codes) with a QR code per registration, and verified the purchase receipts participants submitted.

Tesseract extracted the text and a Groq-hosted LLaMA 3.3 70B validated it against the promotion rules. It ran unattended, on a cron job every 2 minutes, on an AlmaLinux VPS, with nobody reviewing receipts one by one. If nobody reviews, the system has to tell "approved", "rejected" and "I'm not sure" apart, and leave a trail for every decision. And there are three constraints:

  • Each run has a short window. If one execution takes longer than 2 minutes, it overlaps with the next.
  • Memory is shared. The process lives on the same server as the website; if it eats the RAM, it takes the site down.
  • The slow step is external. The LLM call depends on the network and on the provider's limits, not on your CPU.

Receive, queue, process: the web is not a worker

WordPress is built to answer requests, each with a time limit and shared resources. An OCR+LLM pipeline does not fit: Tesseract burns CPU and the remote model depends on the network.

The error I see most in the industry: running OCR and the LLM call inside the web request that receives the upload. It works in the demo. Under a real campaign, every slow inference call holds a PHP worker, the pool fills up, and the site goes down for everyone, including people who were only browsing.

The architecture that works separates three moments:

  • Receive. The web request validates the minimum, stores the file, creates a row in the queue and answers "received" right away.
  • Process. A separate process, triggered by the system cron, takes batches from the queue and runs them through OCR and the LLM.
  • Record. The result is written to the database under rules that MySQL enforces.

That way public pages never find out the pipeline exists: visits do not trigger OCR, internal endpoints require authentication and stay out of the sitemap, and the worker's queries do not compete with the ones that build pages. It is a site with a processing system next to it, not inside it.

A queue in its own table, with explicit states

The pipeline is not a linear script: it is a state machine. Each receipt moves through stages, and each stage can end well, badly, or in doubt.

The temptation in WordPress is to store that state in post meta or wp_options. With thousands of records, don't: wp_options is loaded on every request when it autoloads, and post meta is key-value, so asking for "the oldest pending items" makes MySQL scan far more than it needs to. A dedicated table gives the worker exactly the query it needs:

CREATE TABLE wp_verif_queue (
  id          BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  folio       CHAR(12) NOT NULL,
  status      ENUM('pending','processing','approved','rejected','review','error')
              NOT NULL DEFAULT 'pending',
  attempts    TINYINT UNSIGNED NOT NULL DEFAULT 0,
  claimed_by  CHAR(36) NULL,            -- which run claimed the row
  claimed_at  DATETIME NULL,            -- detects orphaned jobs
  -- The worker always asks for the oldest pending rows: a purpose-built index.
  KEY idx_status_id (status, id),
  UNIQUE KEY uq_folio (folio)           -- one receipt per folio, enforced by MySQL
) ENGINE=InnoDB;

Explicit states leave no ambiguous combinations. And keeping them in the database rather than in memory has three advantages: if the process dies, the next run picks up where it left off; you can reprocess an entire state when a rule changes; and every number on your dashboard comes from a GROUP BY.

The claimed_at column handles a run that dies halfway: if a row has sat in processing too long, it goes back to pending with one more attempt; past the maximum, it moves to error. In a plugin, the table is created with dbDelta() on activation.

An honest note on review: in the real case the pipeline ran without manual review. Even so, I build that exit in from the start: it is cheaper to have the door and not use it than to add it in production.

OCR: quality is decided before Tesseract

Tesseract works much better with clean images: dark text on a light background, at sufficient resolution. A receipt photographed with a phone almost never arrives like that. It comes with shadows, tilt, low light and compression. That is why preprocessing is the highest-return step in the whole pipeline: a language model cannot fix numbers the OCR never read.

from PIL import Image, ImageOps
import pytesseract

def extract_text(path: str) -> tuple[str, float]:
    with Image.open(path) as img:
        img = ImageOps.exif_transpose(img)        # phone photos arrive rotated
        gray = ImageOps.grayscale(img)            # color only adds noise for OCR
        if gray.width < 1500:                     # tiny text = invented characters
            gray = gray.resize((gray.width * 2, gray.height * 2), Image.LANCZOS)
        bw = gray.point(lambda p: 255 if p > 160 else 0)  # threshold: text vs background
        data = pytesseract.image_to_data(bw, lang="spa", config="--psm 6", output_type=pytesseract.Output.DICT)
    confs = [float(c) for c in data["conf"] if float(c) >= 0]
    return " ".join(w for w in data["text"] if w.strip()), (sum(confs) / len(confs) if confs else 0.0)

Rotation comes first: ignore EXIF and Tesseract reads a sideways image and confidently returns garbage. A fixed threshold is a starting point; with highly variable lighting, an adaptive one (for example, with OpenCV) does better, and you choose by measuring against real samples. And the function returns the averaged per-word confidence, the first signal for deciding whether calling the model is worth it at all.

Filter cheap before you spend big: if confidence is very low or the text comes out nearly empty, the receipt does not go to the LLM. Paying a model to read garbage only adds cost and noise. And the image is released when the with block ends: decoded, it takes far more memory than on disk.

LLM: structured output or nothing

The most common mistake is asking the LLM for natural language and searching the answer for keywords. In production, the model changes a comma or adds an explanation, and the parser breaks. Treat the model like an API with a contract: ask for JSON with explicit fields and validate it against a schema before believing a single word:

from pydantic import BaseModel, Field, ValidationError

class Reading(BaseModel):
    is_receipt: bool
    store: str | None = None
    date: str | None = Field(default=None, pattern=r"^\d{4}-\d{2}-\d{2}$")
    total: float | None = Field(default=None, ge=0)
    confidence: float = Field(ge=0, le=1)         # the model says how sure it is

def interpret(raw_response: str) -> Reading | None:
    try:
        return Reading.model_validate_json(raw_response)
    except ValidationError:
        return None    # a response that breaks the contract does not exist

The schema does three jobs at once: it documents what you expect from the model, rejects malformed responses, and converts every field to the right type. What makes the contract sturdier:

  • Put the schema in the prompt. Describe every field, its format, and what to do if it is not in the text: return null, never invent.
  • Use the provider's structured output if it exists. JSON mode drastically reduces malformed responses. Validation is still mandatory.
  • Low temperature. For extracting data you want the most likely answer, not creativity.
  • One retry, not a loop. If the response does not validate, retry once. If it fails again, the receipt goes to error or review.
  • Timeouts and backoff. A remote API will fail some day. One failure should not stop the whole batch.

Deterministic rules after the model

The model reads. It does not decide. That separation is what makes the system auditable. The promotion rules —which stores take part, which dates count, what the minimum amount is— live in code, are applied to the already-validated reading, and every rejection stores a concrete reason.

STORES = {"store-a", "store-b"}             # real catalog, in config, not in the prompt
VALIDITY = ("2026-05-01", "2026-07-31")     # made-up values for the example

def decide(r: Reading, ocr_conf: float) -> tuple[str, str]:
    if not r.is_receipt:
        return "rejected", "does not look like a receipt"
    if r.confidence < 0.7 or ocr_conf < 60:
        return "review", "uncertain reading"  # doubting is a valid outcome
    if (r.store or "").lower() not in STORES:
        return "rejected", "store not in the promotion"
    if not r.date or not (VALIDITY[0] <= r.date <= VALIDITY[1]):
        return "rejected", "date outside the promotion period"
    return "approved", "meets every rule"

What matters is the order: first whatever invalidates everything, then doubt, and finally the business rules. Every outcome returns a readable reason, so when a participant asks why they were rejected, the answer is already in the database. And if a rule changes tomorrow, you do not need to call the model again: just rerun decide over the stored readings.

System cron with flock, not WP-Cron

WP-Cron is not a cron: it is a check WordPress makes when a page loads, and if events are overdue it fires a request to wp-cron.php. With no visits, nothing gets processed; with many, execution depends on traffic, not on a schedule. The fix is to disable it and let the operating system set the pace. The rule that kept the real system stable: a slow batch must never overlap the next one. flock solves that in one line.

⚠️ This touches a production server. Back up the crontab (crontab -l > crontab.bak) before editing, and keep the old line commented so you can roll back in seconds.

# wp-config.php: WP-Cron stops firing on page visits.
#   define( 'DISABLE_WP_CRON', true );

# Site user's crontab: every 2 minutes, never two runs at once.
# flock -n exits immediately if the previous run still holds the lock:
# a slow LLM response delays ONE batch instead of doubling the load.
# timeout kills a hung run before the next slot, so the lock is always freed.
*/2 * * * * flock -n /var/lock/verifier.lock \
  timeout 110 wp --path=/home/site/public_html cron event run --due-now \
  >> /home/site/logs/cron.log 2>&1

# Check which events WordPress has scheduled before changing anything.
wp cron event list --fields=hook,next_run_relative

WP-CLI runs the events outside Apache, without a web request's time limit. Watch out: disabling WP-Cron also stops other plugins' tasks, so the system cron must run every overdue event. To roll back, comment the line and run the process by hand once: the worker is idempotent.

With systemd, a timer gives more control: OnUnitInactiveSec=2min counts from when the previous run finished, output goes to journald, and MemoryMax means that if it overflows, the pipeline dies, not the website.

Claiming work without two processes taking the same thing

flock prevents two cron runs from overlapping. But if you ever run two workers on purpose, you need another guarantee: they never take the same row. The pattern is to claim with an atomic UPDATE and then read only what that worker marked:

// Claim a batch atomically: two workers never take the same row.
global $wpdb;
$token = wp_generate_uuid4();
$wpdb->query( $wpdb->prepare(
    "UPDATE {$wpdb->prefix}verif_queue
        SET status = 'processing', claimed_by = %s, claimed_at = NOW()
      WHERE status = 'pending' ORDER BY id LIMIT %d",
    $token, 25
) );
// Process only what this worker marked with its token.
$batch = $wpdb->get_results( $wpdb->prepare(
    "SELECT id, folio FROM {$wpdb->prefix}verif_queue WHERE claimed_by = %s", $token ) );

MySQL runs the UPDATE as a single operation: each row ends up with one token and there is no window between "read" and "mark" for another process to slip through. The batch is small on purpose: it finishes within the cron window and, if something fails, little is lost.

Uniqueness: the rule lives in MySQL, not in an if

The hardest bug on the project was not in the AI. The Guinness World Record attempt registration needed its own rule: one person, one entry, per activity. The first uniqueness index checked email globally, so the same email could register twice under different activities. The fix was a composite unique index scoped to the activity, with a migration that inspects the schema before altering it. The plugin went from v1.1.0 to v1.1.1.

⚠️ Schema changes in production: take a database dump first (mysqldump --single-transaction) and run the migration in a low-traffic window. Rollback is restoring that dump.

// v1.1.1: uniqueness scoped to the activity. Same email + different activity = valid;
// same email + same activity = rejected by MySQL itself, even under a race.
function registration_migrate_index() {
    global $wpdb;
    $table = $wpdb->prefix . 'record_registration';
    // Idempotent: if the composite index already exists, there is nothing to do.
    if ( $wpdb->get_var( "SHOW INDEX FROM {$table} WHERE Key_name = 'uq_activity_email'" ) ) { return; }
    // A pre-existing duplicate would make the ALTER fail: stop first and log it.
    $dup = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT 1 FROM {$table} GROUP BY activity_id, email HAVING COUNT(*) > 1) d" );
    if ( $dup ) { error_log( "registration: {$dup} duplicates, migration stopped" ); return; }
    // The global (email-only) index is replaced by the composite one in a single ALTER.
    $wpdb->query( "ALTER TABLE {$table} DROP INDEX uq_email, ADD UNIQUE KEY uq_activity_email (activity_id, email)" );
}

Three ideas in that function apply to any system with real data:

  • Idempotency. The migration can run twice without harm, on every plugin update. If the index already exists, it exits.
  • Pre-flight check. If data already violates the new rule, the ALTER would fail halfway. Better to stop, log it and decide calmly.
  • The rule in the database. A PHP if that asks "does this email already exist?" before inserting has a race: two simultaneous requests can both pass the check before either inserts. The unique index does not.

PHP validation is useful for a friendly message; the guarantee comes from MySQL.

Concurrency test: 50 workers at the same slot

A good index is a hypothesis until it survives load. For that module I wrote a standalone verifier and a 15-test suite; one test launched 50 simultaneous workers against the same registration route. Success: exactly one registration per slot and zero server errors. It reproduces in a few lines of Bash:

# 50 simultaneous requests at the same slot: exactly one must win.
# Staging only: never fire this at production.
URL="https://staging.example.test/wp-json/registration/v1/enroll"
seq 50 | xargs -P 50 -I{} curl -s -o /dev/null -w "%{http_code}\n" \
  -X POST "$URL" -H "Content-Type: application/json" \
  -d "{\"activity\":7,\"email\":\"qa@${QA_DOMAIN}\"}" \
  | sort | uniq -c
# Expected: 1 response 201, 49 responses 409 and no 5xx.
# A 500 means MySQL stopped the race, but the plugin did not turn the error into a 409.

The second condition matters as much as the first: if the index stops duplicates but the plugin lets a 500 escape, the rule works and the experience does not. In the real test exactly one registration succeeded per slot with zero server errors, and the module passed 24/24 verifier checks and 15/15 tests. That evidence is what lets you say "done".

Implementation status panel: schema migration, fixed bugs and the 15/15 test suite, without participant data
Implementation status panel: schema migration, fixed bugs and the 15/15 test suite, without participant data

Python: memory, batches and idempotency

Optimizing here rarely means rewriting code: it means knowing where the time goes. If most of it goes to waiting on the LLM, optimizing the Python loop changes nothing; that is why cProfile comes first. And validating a folio is a membership question: in a list it is O(n), in a set O(1) on average. If the pool already lives in MySQL behind a unique index, the database is your set.

Memory. Python frees memory through reference counting, so nothing is released while you hold a reference. The usual leaks: a fetchall() of the whole table, a results list that keeps growing, images nobody closes. Process as a stream:

def pending_receipts(connection, batch=500, cap=5_000):
    """Yield pending rows without loading the whole table."""
    cursor = connection.cursor(dictionary=True)
    # The cap bounds the run: whatever is left goes to the next cron run.
    cursor.execute(
        "SELECT id, image_path FROM receipts "
        "WHERE status = 'pending' ORDER BY id LIMIT %s", (cap,))
    while True:
        rows = cursor.fetchmany(batch)   # memory stays bounded by the batch
        if not rows:
            break
        yield from rows                  # the consumer sets the pace
    cursor.close()

Memory now depends on the batch, not the table. To diagnose, compare two tracemalloc snapshots, one at the start and one after several batches; calling gc.collect() by hand is almost never the fix.

Idempotency and capped concurrency. If two runs process the same receipt, you pay for the LLM twice and write two results. The defenses: the file lock (the same flock, also available as fcntl.flock from Python) and idempotent operations, with each image's hash as the key so a resubmission costs no extra round and is not counted twice. Since OCR runs in a subprocess and the LLM is a network call, the work is I/O-bound: a ThreadPoolExecutor with few workers does the job, even with the GIL, while a single thread writes to MySQL. Watch out: pool.map consumes the whole generator when it queues tasks, which is why the query has a cap. The number of workers is tuned to the provider's rate limit, not to gut feeling.

When one VPS is no longer enough

The bottleneck is the slowest stage, and it is rarely the Python loop. When one VPS is no longer enough, I split OCR and LLM calls into separate containers, each with its own memory limit, so the OOM killer takes down one worker and not the website: for example, four OCR replicas and two LLM replicas behind a queue. Why fewer for the LLM? Because the inference provider sets the ceiling, and adding workers past the rate limit only adds retries.

Observability: trusting the system weeks later

  • Store everything in between. OCR text, confidence, the model's raw response, the validated reading and the decision. Without that, an error cannot be reproduced.
  • Version the prompt and the rules. Every decision records which version produced it.
  • Build a labeled sample set. A few dozen real receipts with the correct answer; every change to preprocessing, prompt or model is measured against them before deploying.
  • Measure per state and per batch, not per log line, and alert on trends: a pending queue that grows run after run warns you before anyone complains.

You do not need an expensive platform: a query grouped by state and by hour, checked by a script that alerts when something falls out of range, covers most cases.

What I would NOT do

  • Let the LLM approve or reject, or put the rules in the prompt. A language model can be confidently wrong, and "the model said so" is not an audit trail.
  • Send raw images to OCR and blame the model. If the extracted text is bad, no prompt will fix it.
  • Parse free text with regular expressions. Demand JSON and validate it.
  • Process the file in the same request that receives it. Receive, queue and respond.
  • Trust uniqueness to a prior check in PHP, or migrate the schema without a backup and a duplicate check.
  • Load everything into memory "because it fits" or parallelize without a limit. Hundreds of threads against the LLM only trip the rate limit and make cost unpredictable.
  • Start with Kubernetes for a single campaign. A cron job with flock on one VPS handled an 80,000-folio pool. I split into services when OCR and inference genuinely need to scale apart, because every extra moving part is one more thing to monitor at 3 a.m.

FAQ

Why not use WP-Cron for an OCR+LLM pipeline?
Because it only fires when someone visits the site: with no traffic nothing gets processed, and with heavy traffic it can launch overlapping runs. Disable it and call the events from the system cron, with flock.
How do I force an LLM to always answer in the same format?
Ask for JSON with explicit fields, use the provider's structured output if it exists, and validate with a schema, for example pydantic. If it fails, retry once or send it to review.
What preprocessing does an image need before Tesseract?
Fix the rotation, convert to grayscale, upscale if it is small, and apply a threshold. Every step is measured against real samples.
Can I keep the queue in wp_options or post meta?
For a handful of tasks, yes; for thousands, no. A dedicated table with its own index answers the worker's query without affecting the rest of the site.
Threads or processes?
If OCR runs in a subprocess and the LLM is a remote API, threads. If OCR runs inside the same Python process and saturates a core, processes.
How do I test that my registration endpoint handles simultaneous requests?
On staging, fire many requests at the same slot and count the responses: exactly one must win, the rest must get a controlled rejection, and none should return a server error.

Next step

A reliable OCR+LLM pipeline is not chaining two calls: it is designing states, preparing the input, holding the model to a contract, deciding in code, and letting MySQL enforce the rules. The full system is in the Panini Fan Zone case study, and if you want to bring AI into a real process, take a look at the AI automation service.

Have a document flow that still depends on someone reading receipts by hand? Send me one anonymized sample and the rules it has to pass. I'll tell you which part belongs to OCR, which part to an LLM, and which part should stay a rule in code. Write to me. Get a quote on WhatsApp in 2 min

Samuel Torres Pichardo

Samuel Torres Pichardo
Software and cloud engineer in Mexico City, with about 3 years of professional experience.
About me · LinkedIn · GitHub · Contact

Got a project in mind?

Hire me: I'll help you build it.

Websites, online stores, custom systems and cloud. Tell me what you need and I'll tell you how I'd build it, what it costs and how long it takes.

  • Mexico City · remote

Menu

Español

samuelnegociosnegocios@gmail.com