Celery: tareas en segundo plano

Guía para evitar race conditions en tareas Celery con Django: transaction.on_commit, sin Sleep, definición de parámetros por nombre y mejor observabilidad con Flower; prácticas seguras y pruebas deterministas.

16 ago 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-
2. Celery

En muchas aplicaciones Django se tiende a utilizar sleep dentro de una tarea de Celery para evitar condiciones de carrera cuando la tarea intenta leer datos que acaban de crearse en la base de datos. Por ejemplo, reconstruir etiquetas tras crear un usuario y añadir sleep para esperar a que la transacción se complete no es una solución fiable ni recomendable.

El uso de sleep es frágil porque depende de tiempos arbitrarios, ralentiza el sistema y oculta el verdadero origen del problema. Si la tarea rebuild_tags recibe only student_id y espera un segundo con sleep para luego consultar el modelo User puede funcionar a veces y fallar otras, sobre todo bajo carga o con latencias variables entre servicios.

La forma correcta es asegurar que la tarea se lanza solo cuando la transacción que crea los datos ha sido confirmada. Django proporciona transaction.on_commit para ejecutar un callable justo después del commit de la transacción. En la práctica se usa transaction.on_commit con una llamada que lanza la tarea de Celery, por ejemplo pasando una función que invoque rebuild_tags.delay con los argumentos necesarios. De este modo se evita sleep y se garantiza que la tarea ve los datos persistidos.

Otro detalle importante es cómo se definen los parámetros de la tarea para que herramientas como Flower muestren argumentos claros. Si queremos que los parámetros nombrados aparezcan en kwargs conviene forzar parámetros solo por nombre usando sintaxis que acepte args extras y luego parámetros keyword only, por ejemplo aceptar cualquier cosa con asterisco y declarar student_id como argumento por nombre. Así en Flower la tarea se verá como args vacíos y kwargs con student_id igual a un valor, lo cual mejora la legibilidad y el diagnóstico.

En escenarios con celery beat y tareas programadas es habitual enviar argumentos serializables en formato json. Para evitar confusiones es recomendable declarar parámetros por nombre con valores por defecto y pasar en la programación algo similar a {hour:17, minute:47} para indicar la hora y el minuto deseados. De esta manera la tarea recibe parámetros explícitos y el comportamiento es predecible.

Nota sobre pruebas TDD: si durante los tests aparece sleep es señal de que la prueba o el código no están aislando la transacción correctamente. En pruebas unitarias conviene usar transaction.on_commit o simular el comportamiento de lanzamiento de tareas para evitar sleeps y hacer tests deterministas y rápidos.

En Q2BSTUDIO, empresa especialista en desarrollo de software a medida y aplicaciones a medida, aplicamos estas buenas prácticas en arquitecturas con Celery para garantizar fiabilidad y escalabilidad. Ofrecemos servicios integrales que incluyen software a medida, inteligencia artificial e ia para empresas, agentes IA, ciberseguridad, servicios cloud aws y azure y servicios inteligencia de negocio. También implementamos soluciones analíticas con power bi y acompañamos a los equipos en la adopción de prácticas de despliegue seguro y pruebas automatizadas.

Si buscas optimizar procesos asíncronos, evitar race conditions y mejorar la observabilidad de las tareas con Celery, contacta con Q2BSTUDIO para diseñar e implementar soluciones robustas, seguras y escalables en software a medida, inteligencia artificial, ciberseguridad y servicios cloud aws y azure.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat