How I Shipped Secure Excel (.xlsx) Uploads & Multi-Provider AI Failover (Gemini Groq) on a $0 512MB Container
In my previous Dev.to post, I shared how I built AskGrid — a privacy-first AI spreadsheet analyst where only column schemas go to the LLM, deterministic Python/Pandas runs all calculations, and an automated 18-case evalu
In my previous Dev.to post, I shared how I built AskGrid — a privacy-first AI spreadsheet analyst where only column schemas go to the LLM, deterministic Python/Pandas runs all calculations, and an automated 18-case evaluation harness keeps accuracy verifiable.
Since then, I shipped AskGrid v1.1.2 live at https://askgrid.pages.dev/ (source code: github.com/niRmana11/askgrid, zero login required, 1-click sample dataset).
While upgrading from CSV-only v1.0.0 to native Excel (.xlsx) support and preparing for launch, I hit four real-world production surprises that no tutorial warns you about. Here is each one and the exact fix.
1. Why Accepting .xlsx on a 512MB Container Is a Security Minefield
My first realization after shipping v1.0.0 was simple: most non-coders work in .xlsx, not .csv. Asking them to open Excel, export a CSV, and re-upload kills trial conversion before Question #1.
The catch is that an .xlsx file is not a flat text file — it is a ZIP archive full of XML files. On a free 512MB RAM container (--workers 1), naive pd.read_excel() opens three immediate failure modes:
-
ZIP Bombs: A 100 KB
.xlsxupload can decompress into gigabytes of XML and OOM-kill the container before Pandas even sees row 1. -
Macro-Enabled & Legacy Formats:
.xlsmfiles carry VBA macro binaries (vbaProject.bin), and someone can simply renamemalware.xlsmtoreport.xlsx. - Repeated XML Re-Parsing: Re-parsing Excel XML on every follow-up question wastes RAM and latency.
The Fix: Pre-Parse ZIP Inspection + Disk-Backed CSV Storage
Before openpyxl ever touches an uploaded .xlsx, AskGrid validates the raw ZIP header, entry count, macro binaries, and total uncompressed XML size:
_ZIP_MAGIC = b"PK\x03\x04"
_MAX_ZIP_ENTRIES = 500
def _validate_xlsx_archive(raw_bytes: bytes, *, max_uncompressed_mb: int = 50) -> None:
if not raw_bytes.startswith(_ZIP_MAGIC):
raise CSVParseError("Invalid Excel file. Please upload a valid .xlsx workbook or .csv file.")
with zipfile.ZipFile(io.BytesIO(raw_bytes)) as zf:
infos = zf.infolist()
if len(infos) > _MAX_ZIP_ENTRIES:
raise CSVParseError("Excel workbook contains too many internal files.")
total_uncompressed = 0
max_uncompressed_bytes = max_uncompressed_mb * 1024 * 1024
for info in infos:
if info.filename.lower().endswith("vbaproject.bin"):
raise CSVParseError(
"Macro-enabled Excel files (.xlsm) are not allowed for security."
)
total_uncompressed += info.file_size
if total_uncompressed > max_uncompressed_bytes:
raise CSVParseError(
f"Excel file expands beyond the {max_uncompressed_mb} MB safety limit."
)
Once validated, we stream rows with openpyxl.load_workbook(..., read_only=True, data_only=True) (which reads cached formula values and enforces max_rows / max_columns early), then serialize the active sheet to a clean UUIDv4 /tmp/<uuid4>.csv file (0 MB idle RAM). Every subsequent /ask query reads clean CSV in ~5 ms instead of re-parsing Excel XML — and multi-sheet workbooks expose an inline sheet switcher cleanly.
2. The Sneaky defusedxml Docker Trap
openpyxl's documentation recommends installing defusedxml to block XML Entity Expansion ("Billion Laughs" / XXE) attacks on untrusted .xlsx files.
During my pre-release security audit, I ran:
uv run python -c "import openpyxl; print('DEFUSEDXML:', openpyxl.DEFUSEDXML)"
# Output: DEFUSEDXML: True
Looks safe, right? Wrong! Out of curiosity, I checked why defusedxml was installed:
uv tree --invert --package defusedxml
defusedxml v0.7.1
└── py-serializable v2.2.0
└── cyclonedx-python-lib v11.12.0
└── pip-audit v2.10.1
└── askgrid-server v0.1.0 (group: dev)
Huge catch: Locally, openpyxl.DEFUSEDXML was only True by accident because pip-audit (a dev-only dependency) pulled defusedxml in! In my production Dockerfile:
RUN uv sync --frozen --no-dev
pip-audit is excluded — meaning defusedxml would have silently vanished in production Docker!
Fix: uv add defusedxml to pin defusedxml>=0.7.1 in production dependencies, plus a unit test (assert openpyxl.DEFUSEDXML is True) so it can never regress silently.
3. Surviving Real Free-Tier AI Outages & Geo-Blocks (Zero New Dependencies!)
Five minutes before I planned to share v1.1.0, I ran a live sanity check on https://askgrid.pages.dev/ — and got 503 Service Unavailable!
Adding safe metadata-only status logging (logging only model name + HTTP status code + upstream error type, never keys or prompts) uncovered two real production failures at once:
-
Global Free-Tier
503Spikes + SDK Retry Amplification: Locally, Google's Gemini 3.x models were hitting temporary503 UNAVAILABLEhigh-demand spikes — andgoogle-genai's internaltenacityretry loop retried 5× per model (~45s hang before failing over!). - Hidden Cloud IP Geo-Block: On Render's Singapore region, all 5 Gemini models failed immediately with:
ClientError code=400 status=FAILED_PRECONDITION msg=User location is not supported for the API use.
The Fix: Fast Failover (Gemini → Groq) Behind AIProvider + Region Move
Because Phase 1 had already abstracted AI behind a provider-agnostic AIProvider Protocol (services/ai/base.py), adding a second free-tier provider required zero changes to the Pandas engine or React frontend — and zero new PyPI dependencies:
-
Disabled Gemini SDK retry amplification with
types.HttpRetryOptions(attempts=1)so failed models trip theModelCircuitBreakerand fail over in<1s. -
Built
GroqAIProviderusing Python stdliburllib.request(json_objectmode +AnalysisIntent.model_json_schema()+ strict Pydantic v2 validation + explicitUser-Agent: AskGrid/1.1header). -
Wrapped both in
FallbackAIProvider([GeminiAIProvider, GroqAIProvider])— still strictly schema-only (zero raw rows sent to either provider!). -
Migrated the Render Docker service from Singapore → Oregon (US West) — instantly eliminating Google's
400 FAILED_PRECONDITIONgeo-block so all 8 models (5 Gemini + 3 Groq) work together at $0.
4. Cross-Model Prompt Hardening (v1.1 → v1.2) & Live Groq Eval Scorecard
Switching models immediately exposed a classic cross-model prompt bug: Gemini had been forgiving when Rule 9 of v1.1 didn't explicitly state that top_n requires group_by, whereas Groq's openai/gpt-oss-120b strictly left group_by=None and got rejected by intent_validator.py.
Rather than patching one symptom, I audited every single one of the 10 operations against intent_validator.py and engine.py, bumped PROMPT_VERSION = "v1.2", and added --provider gemini|groq to evals/run_evals.py.
Running all 18 golden cases live against the Groq failover chain (openai/gpt-oss-120b, qwen/qwen3.8-27b, openai/gpt-oss-20b) produced:
| Metric |
v1.0 (Gemini) |
v1.1 (Gemini) |
v1.2 (Groq Failover Chain) |
|---|---|---|---|
| Intent Accuracy | 17/18 (94.4%) | 18/18 (100.0%) | 17/17 answered (100.0%)* |
| End-to-End Exact Pandas Math | 14/15 (93.3%) | 15/15 (100.0%) | 15/15 (100.0%) |
| Safety & Prompt-Injection Refusals | 3/3 (100.0%) | 3/3 (100.0%) | 2/2 answered* |
| Median Latency (p50) | 1.74s | 1.17s | 0.93s |
*At --sleep 1.5, the Circuit Breaker fired live twice on Groq 429 TPM limits (gpt-oss-120b → qwen3.8-27b → gpt-oss-20b) and kept answering with 100% exact Pandas math across all 15 computable cases; only Q18 hit the 1-minute bucket across all 3 models.
Try It Live & Tell Me What Breaks!
You can test AskGrid v1.1.2 right now (upload a messy .xlsx or .csv, or click Try Sample Dataset — no signup needed):
- Live App: https://askgrid.pages.dev/
- Source Code: https://github.com/niRmana11/askgrid
If you run FastAPI/Pandas in small containers or handle multi-provider LLM failover in production, I'd love to hear how you handle XML security or token-per-minute limits in the comments!
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.