惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
Y
Y Combinator Blog
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
S
SegmentFault 最新的问题
IT之家
IT之家
Recent Announcements
Recent Announcements
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
T
The Blog of Author Tim Ferriss
Martin Fowler
Martin Fowler
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
WordPress大学
WordPress大学
博客园 - Franky
L
LangChain Blog
人人都是产品经理
人人都是产品经理
小众软件
小众软件
博客园 - 叶小钗
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell
大猫的无限游戏
大猫的无限游戏
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
雷峰网
雷峰网
腾讯CDC
Google DeepMind News
Google DeepMind News
博客园 - 三生石上(FineUI控件)
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Help Net Security
Help Net Security
C
Check Point Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
N
News and Events Feed by Topic
V2EX - 技术
V2EX - 技术
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Schneier on Security
Schneier on Security
博客园 - 聂微东
A
Arctic Wolf
H
Heimdal Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
C
Cyber Attacks, Cyber Crime and Cyber Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Google DeepMind News
Google DeepMind News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Día 8: El usuario subió un Excel y tu servidor pidió perdón
Alejandro La · 2026-04-24 · via DEV Community

El usuario sube un Excel con 500.000 filas. Tu endpoint lo lee, lo procesa, y le devuelve el resultado. Sincrónicamente. En el mismo thread del request HTTP.

El browser muestra "esperando respuesta del servidor" durante 4 minutos. El load balancer corta por timeout a los 60 segundos. La app se come 2GB de memoria. El pod se reinicia. El usuario vuelve a intentar. Y así tres veces.

Si esto te suena familiar, seguí leyendo.

HTTP no fue diseñado para esto

Antes de hablar de código, necesitamos hablar de algo más fundamental: HTTP es un protocolo de request-response diseñado para respuestas rápidas. Millisegundos, tal vez segundos. No minutos.

Cuando metés una operación de 4 minutos dentro de un request HTTP, estás peleando contra todo el stack:

  • El load balancer tiene un timeout (generalmente 60 segundos)
  • El proxy tiene un timeout
  • El browser tiene un timeout
  • La conexión TCP tiene un timeout
  • Tu thread pool tiene un límite de threads

Todo conspira contra vos. Y no es un bug — es que estás usando la herramienta equivocada para el trabajo.

Es como mandar un paquete de 200 kilos por correo postal. Técnicamente podrías. Pero no fue diseñado para eso. Necesitás un flete.

El patrón universal: recibí, encolá, procesá, notificá

La solución no es "hacer que tarde menos". La solución es cambiar la arquitectura. Y el patrón es el mismo en cualquier lenguaje:

1. RECIBIR  → Aceptar el request, validar lo básico
2. ENCOLAR  → Generar un ID de job, responder inmediatamente
3. PROCESAR → En background, en batches, con progreso
4. NOTIFICAR → El usuario consulta el estado o recibe una notificación

Enter fullscreen mode Exit fullscreen mode

Esto existe en todos lados:

  • Python/Django: Celery + Redis como broker
  • Node.js: Bull/BullMQ con Redis, o AWS SQS
  • Go: Goroutines + channels, o temporal.io para workflows complejos
  • Ruby/Rails: Sidekiq
  • Java/Spring: @Async + ThreadPoolExecutor, o Spring Batch para escenarios pesados
  • .NET: Hangfire, o Azure Functions

La herramienta cambia. El patrón es idéntico: no proceses en el thread del request HTTP.

El crimen contra la arquitectura

Mirá este endpoint. Parece inocente. Es un desastre:

@PostMapping("/importar")
public ResponseEntity<String> importar(@RequestParam MultipartFile archivo) {
    List<Registro> registros = parser.parsear(archivo); // 500K filas en memoria
    for (Registro r : registros) {
        validar(r);
        transformar(r);
        guardar(r);               // 500K INSERTs, uno por uno
    }
    return ResponseEntity.ok("Listo");
}

Enter fullscreen mode Exit fullscreen mode

Contemos los problemas:

  1. Todo en memoria: 500K objetos Java. Si cada uno pesa 1KB, son 500MB solo en datos. Más los objetos temporales, fácilmente llegás a 2GB.
  2. Todo secuencial: un registro a la vez. Si cada INSERT tarda 2ms, son 1000 segundos. Más de 16 minutos.
  3. Todo síncrono: el usuario espera con el browser abierto. El thread HTTP queda bloqueado.
  4. Cero feedback: el usuario no sabe si va por el registro 100 o el 499.999.
  5. Todo o nada: si falla en la fila 499.999, ¿perdiste todo? ¿Hacés rollback de 499.998 registros?

La versión que respeta al usuario (y al servidor)

Paso 1: Recibí y respondé inmediatamente

@PostMapping("/importar")
public ResponseEntity<ImportacionResponse> importar(
        @RequestParam MultipartFile archivo) {

    String jobId = importacionService.encolar(archivo);

    return ResponseEntity.accepted().body(
        new ImportacionResponse(jobId, "PROCESANDO",
            "/importaciones/" + jobId + "/estado")
    );
}

Enter fullscreen mode Exit fullscreen mode

El usuario sube el archivo y en menos de un segundo recibe un ID de trabajo y una URL para consultar el progreso. No espera. No hay timeout. No hay pantalla de "cargando" durante 4 minutos.

HTTP 202 Accepted — "recibí tu pedido, te aviso cuando esté". Ese es el status code correcto para operaciones asíncronas. No 200. No 201. 202.

Paso 2: Procesá en background por batches

@Async("importacionExecutor")
public void procesar(String jobId, Path archivoPath) {
    Importacion importacion = repository.findByJobId(jobId);
    importacion.setEstado("EN_PROGRESO");

    try (Stream<Registro> registros = parser.stream(archivoPath)) {
        List<Registro> batch = new ArrayList<>(1000);
        int procesados = 0;

        for (Registro r : registros) {
            try {
                batch.add(transformar(validar(r)));
            } catch (ValidationException e) {
                importacion.incrementarErrores();
            }

            if (batch.size() >= 1000) {
                repository.saveAll(batch);  // UN saveAll cada 1000
                batch.clear();
                procesados += 1000;
                importacion.setProcesados(procesados);
                repository.save(importacion);
            }
        }

        // Guardar ultimo batch parcial
        if (!batch.isEmpty()) {
            repository.saveAll(batch);
        }

        importacion.setEstado("COMPLETADO");
    } catch (Exception e) {
        importacion.setEstado("ERROR");
    }
    repository.save(importacion);
}

Enter fullscreen mode Exit fullscreen mode

Tres cosas clave cambiaron:

  1. Stream en vez de lista: no cargás 500K filas en memoria. Las leés de a poco. En Python es un generator. En Node es un readable stream. En Go es un scanner.
  2. Batches de 1000: en vez de un INSERT por fila, hacés un saveAll cada 1000 registros. La base de datos te lo agradece — un bulk insert de 1000 es mucho más rápido que 1000 inserts individuales.
  3. Progreso persistido: el usuario puede consultar cuántas filas se procesaron y cuántas fallaron. Sin adivinar.

Paso 3: Configurá el thread pool

@Bean("importacionExecutor")
public Executor importacionExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(4);
    executor.setQueueCapacity(10);
    executor.setThreadNamePrefix("import-");
    executor.setRejectedExecutionHandler(
        new ThreadPoolExecutor.CallerRunsPolicy()
    );
    return executor;
}

Enter fullscreen mode Exit fullscreen mode

No uses el executor por defecto. Si no configurás un pool, Spring crea un thread nuevo por cada tarea. Con 50 usuarios subiendo archivos a la vez, tenés 50 threads compitiendo por CPU y memoria. Eso no escala.

El CallerRunsPolicy es elegante: si la cola está llena, en vez de tirar un error, ejecuta la tarea en el thread del caller. Funciona como back-pressure natural. "Estoy ocupado, hacelo vos."

Decile al usuario qué está pasando

La UX importa tanto como la arquitectura. El peor error es dejar al usuario adivinando.

{
  "jobId": "abc-123",
  "estado": "EN_PROGRESO",
  "totalRegistros": 500000,
  "procesados": 125000,
  "errores": 42,
  "porcentaje": 25,
  "tiempoEstimado": "3 minutos"
}

Enter fullscreen mode Exit fullscreen mode

El frontend hace polling cada 5 segundos (o mejor: usa WebSocket/SSE) y muestra una barra de progreso real. El usuario ve que algo está pasando. No se pone ansioso. No recarga la página. No genera requests duplicados.

Esto aplica a cualquier framework y cualquier frontend. La respuesta JSON con progreso es universal.

La regla de los tres tiempos

Si tu operación tarda segundos, puede ser síncrona. Respondé en el request, nadie se queja.

Si tarda minutos, tiene que ser asíncrona. Recibí, encolá, procesá en background, notificá.

Si tarda horas, necesitás un sistema de colas dedicado (RabbitMQ, SQS, Kafka) o un framework de batch processing (Spring Batch, Celery, Temporal). Y probablemente necesitás retry, dead letter queue, y monitoreo.

No es una cuestión de elegancia. Es que HTTP no fue diseñado para operaciones de larga duración. El timeout del load balancer, el timeout del browser, el timeout del proxy — todo te va a explotar en la cara si intentás forzar una operación de minutos en un protocol de milisegundos.

Cuándo NO usar async

  • Operaciones que tardan menos de 5 segundos — La complejidad del async no se justifica. Dejalo síncrono.
  • Cuando el usuario necesita el resultado para continuar — Si el paso siguiente depende del resultado, async no ayuda. El usuario va a quedarse esperando igual, pero haciendo polling.
  • Sin infraestructura para monitoreo — Los jobs async que fallan silenciosamente son un clásico de terror. Si no podés ver los jobs fallidos, estás volando a ciegas.
  • Con archivos pequeños — 100 registros no justifican toda esta maquinaria. Procesalos síncrono, respondé en 200ms, y seguí con tu vida.

Esto es el Día 8

Este artículo es parte de #100ArchitectureDays — una serie de problemas reales de arquitectura con soluciones reales. Si tu endpoint tiene un timeout de 4 minutos, no necesitás un timeout más largo. Necesitás otra arquitectura.

Y lo más importante: tratá al usuario como adulto. Decile "esto tarda 3 minutos" y mostrále el progreso. Es mil veces mejor que una pantalla en blanco con un spinner eterno.

Seguí la saga completa en #100ArchitectureDays.

Todo el código está en GitHub. Si te está sirviendo, dejame una estrella — es gratis y ayuda a que más gente lo encuentre.