SlideShare a Scribd company logo
1 of 10
Python Application Development
Web Development packages
• Flask - Backend framework
• SQLAlchemy - ORM
• Celery - Task Queue
• Pydantic - Validation
• dashboard-support-py - Internal Authentication
• uWSGI - WSGI complaint web server
• tensorflow_model_server - Deploy models in production
• Redis - In-memory key–value
database
• docker - containerization
Flaskname inspired from bottle
• WSGI compliant microframework, with no batteries included. Gives developer utmost flexibility.
• Not suitable for large codebases where MVC structure makes organization easier.
• Includes development server for quick development, that should not be used in production
• Does not come with ORM and is most commonly used with SQLAlchemy.
• Good Practices:
• Use application factory and blueprints for organizing feature level code.
• Use existing exception classes and status code instead of rewriting them again.
• Add logging to all exceptions.
• Application and Request Contexts
• Application context and request contexts are pushed in order for each request.
• Flask has several thread-local variables like current_app(proxy to application context),
request(proxy to request context) and g which hold reference to any object like
database_connection throughout the entire request-response cycle.
• Contexts should always be pushed before accessing these current_app and request variables
or you would end up with common RuntimeError: Working outside of request context.
Celery
• Commonly used task queue library in python with
support for many brokers RabbitMQ, Redis, SQS etc.,
• Task names with arguments are serialized (supports
json, pickle) and sent over the network to broker
• Support for multiple execution pools, like prefork
(multiprocessing), solo (single process), eventlet,
gevent
• Has signal handling mechanisms for SIGTERM
• Redis as a Broker
• Task messages concerning a queue are stored as
list. Number of pending tasks can be found by
issuing LLEN from redis-cli or client library.
• New tasks are pushed with LPUSH by producer
• Tasks are prefetched by workers using BRPOP
Celery Good Practices
• Keep tasks idempotent as much as possible(retry should always produce same results).
• Common exceptions like network errors, should be caught and retried with exponential backoff
• Create a subclass of BaseTask and add handlers for task success, failure, return and retries.
• Use send_task or signature methods importing of calling task’s apply_async or delay methods.
• Use Signals for decoupling application logic with tracking/cleanup logic. Signals are executed either
in producer process or worker MainProcess/ForkProcess depending on execution pool
• Useful signals include after_task_publish, task_prerun, celeryd_init, worker_process_init
• Don’t use result_backend in production(if the process that called it doesn’t wait on its result) for
performance improvement.
• Good Configuration to start with
• worker_prefetch_multiplier = 1
• task_acks_late = True
• task_reject_on_worker_lost = False
• worker_max_tasks_per_child = 2000
• task_ignore_result = True
• task_soft_time_limit = 120
• task_time_limit = 180
Deployment
• flask
• uWSGI
• WSGI compliant production grade web server with limited community support.
• Has many configuration options and legacy defaults which are difficult to tune for
specific use cases.
• mod_wsgi with Apache
• Model inference
• Tensorflow model server
• High-performant model server with batching support for better utilization of hardware
resources. Exposes grpc and REST APIs natively. Recommended to use gRPC API.
• gRPC
• Has language agnostic implementation with similar API in different languages
• Serializes the request body using protocol buffers resulting in low network payload
• Uses faster HTTP/2 protocol underneath, and has its own advantages over HTTP/1.1
Profiling
• Profile your applications to find where it’s spending time and optimise those areas.
• Work by periodically collecting samples of execution point of a process by interrupting the
OS.
• py-spy is one such profiler specific to python. Produces nice flame graphs and stack traces
Docker - PID 1 case
• Scaling up/down mechanisms for load balancing should be designed carefully for containers.
• Docker sends the SIGTERM signals(handlers inside application defined by application developers)
to the running containers for graceful shutdowns while scaling down. If the container does not
shutdown in the predefined duration after cleaning up (10-30 seconds), docker sends SIGKILL.
• Docker runs the process defined in ENTRYPOINT with PID 1 and passes all the signals to this
process. This has certain limitations:
• If the ENTRYPOINT is defined as /bin/bash -c celery -A celery_app worker or entrypoint.sh,
shell gets PID 1 with celery as its child process(different PID).
• Shell behaves differently when it is run as init process. It ignores SIGTERM/SIGINT signals.
• So the child process (celery) doesn’t receive any signal and continues to pick more tasks from
the broker. Finally, when the SIGKILL is sent, worker exits instantaneously leading in process
failures.
• Solution:
• Use exec to run the command inside entrypoint.sh like exec celery -A celery_app worker
inside entrypoint.sh This replaces the bash process and takes PID 1.
• If required, lightweight init system like tini (which takes PID 1) can also be used on top of this
as they have signal passing capabilities to child processes.
References
• https://hynek.me/articles/docker-signals/
• https://docs.celeryq.dev/en/stable/userguide/signals.html
• https://blog.wolt.com/engineering/2021/09/15/5-tips-for-writing-production-ready-celery-tasks/
• https://www.youtube.com/watch?v=kUz2zjkKxFg
• https://www.youtube.com/watch?v=IvsANO0qZEg

More Related Content

Similar to python_development.pptx

Splunk: Forward me the REST of those shells
Splunk: Forward me the REST of those shellsSplunk: Forward me the REST of those shells
Splunk: Forward me the REST of those shellsAnthony D Hendricks
 
12 Factor App Methodology
12 Factor App Methodology12 Factor App Methodology
12 Factor App Methodologylaeshin park
 
Cerberus : Framework for Manual and Automated Testing (Web Application)
Cerberus : Framework for Manual and Automated Testing (Web Application)Cerberus : Framework for Manual and Automated Testing (Web Application)
Cerberus : Framework for Manual and Automated Testing (Web Application)CIVEL Benoit
 
Cerberus_Presentation1
Cerberus_Presentation1Cerberus_Presentation1
Cerberus_Presentation1CIVEL Benoit
 
Latest (storage IO) patterns for cloud-native applications
Latest (storage IO) patterns for cloud-native applications Latest (storage IO) patterns for cloud-native applications
Latest (storage IO) patterns for cloud-native applications OpenEBS
 
Fluo CICD OpenStack Summit
Fluo CICD OpenStack SummitFluo CICD OpenStack Summit
Fluo CICD OpenStack SummitMiguel Zuniga
 
CON5451_Brydon-OOW2014_Brydon_CON5451 (1).pptx
CON5451_Brydon-OOW2014_Brydon_CON5451 (1).pptxCON5451_Brydon-OOW2014_Brydon_CON5451 (1).pptx
CON5451_Brydon-OOW2014_Brydon_CON5451 (1).pptxSergioBruno21
 
How kubernetes operators can rescue dev secops in midst of a pandemic updated
How kubernetes operators can rescue dev secops in midst of a pandemic updatedHow kubernetes operators can rescue dev secops in midst of a pandemic updated
How kubernetes operators can rescue dev secops in midst of a pandemic updatedShikha Srivastava
 
Modern application development with oracle cloud sangam17
Modern application development with oracle cloud sangam17Modern application development with oracle cloud sangam17
Modern application development with oracle cloud sangam17Vinay Kumar
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Pavel Chunyayev
 
Frameworkless CLI app in PHP
Frameworkless CLI app in PHPFrameworkless CLI app in PHP
Frameworkless CLI app in PHPMax Bodnar
 
Service-Level Objective for Serverless Applications
Service-Level Objective for Serverless ApplicationsService-Level Objective for Serverless Applications
Service-Level Objective for Serverless Applicationsalekn
 
Docker Swarm and Traefik 2.0
Docker Swarm and Traefik 2.0Docker Swarm and Traefik 2.0
Docker Swarm and Traefik 2.0Jakub Hajek
 
Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502kaziul Islam Bulbul
 
The twelve factor app
The twelve factor appThe twelve factor app
The twelve factor appInthra onsap
 
High Volume Payments using Mule
High Volume Payments using MuleHigh Volume Payments using Mule
High Volume Payments using MuleAdhish Pendharkar
 
Security of Oracle EBS - How I can Protect my System (UKOUG APPS 18 edition)
Security of Oracle EBS - How I can Protect my System (UKOUG APPS 18 edition)Security of Oracle EBS - How I can Protect my System (UKOUG APPS 18 edition)
Security of Oracle EBS - How I can Protect my System (UKOUG APPS 18 edition)Andrejs Prokopjevs
 
Performance management
Performance managementPerformance management
Performance managementAlan Lok
 
Running Airflow Workflows as ETL Processes on Hadoop
Running Airflow Workflows as ETL Processes on HadoopRunning Airflow Workflows as ETL Processes on Hadoop
Running Airflow Workflows as ETL Processes on Hadoopclairvoyantllc
 

Similar to python_development.pptx (20)

Splunk: Forward me the REST of those shells
Splunk: Forward me the REST of those shellsSplunk: Forward me the REST of those shells
Splunk: Forward me the REST of those shells
 
12 Factor App Methodology
12 Factor App Methodology12 Factor App Methodology
12 Factor App Methodology
 
Cerberus : Framework for Manual and Automated Testing (Web Application)
Cerberus : Framework for Manual and Automated Testing (Web Application)Cerberus : Framework for Manual and Automated Testing (Web Application)
Cerberus : Framework for Manual and Automated Testing (Web Application)
 
Cerberus_Presentation1
Cerberus_Presentation1Cerberus_Presentation1
Cerberus_Presentation1
 
Latest (storage IO) patterns for cloud-native applications
Latest (storage IO) patterns for cloud-native applications Latest (storage IO) patterns for cloud-native applications
Latest (storage IO) patterns for cloud-native applications
 
Fluo CICD OpenStack Summit
Fluo CICD OpenStack SummitFluo CICD OpenStack Summit
Fluo CICD OpenStack Summit
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
 
CON5451_Brydon-OOW2014_Brydon_CON5451 (1).pptx
CON5451_Brydon-OOW2014_Brydon_CON5451 (1).pptxCON5451_Brydon-OOW2014_Brydon_CON5451 (1).pptx
CON5451_Brydon-OOW2014_Brydon_CON5451 (1).pptx
 
How kubernetes operators can rescue dev secops in midst of a pandemic updated
How kubernetes operators can rescue dev secops in midst of a pandemic updatedHow kubernetes operators can rescue dev secops in midst of a pandemic updated
How kubernetes operators can rescue dev secops in midst of a pandemic updated
 
Modern application development with oracle cloud sangam17
Modern application development with oracle cloud sangam17Modern application development with oracle cloud sangam17
Modern application development with oracle cloud sangam17
 
Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015Ansible benelux meetup - Amsterdam 27-5-2015
Ansible benelux meetup - Amsterdam 27-5-2015
 
Frameworkless CLI app in PHP
Frameworkless CLI app in PHPFrameworkless CLI app in PHP
Frameworkless CLI app in PHP
 
Service-Level Objective for Serverless Applications
Service-Level Objective for Serverless ApplicationsService-Level Objective for Serverless Applications
Service-Level Objective for Serverless Applications
 
Docker Swarm and Traefik 2.0
Docker Swarm and Traefik 2.0Docker Swarm and Traefik 2.0
Docker Swarm and Traefik 2.0
 
Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502
 
The twelve factor app
The twelve factor appThe twelve factor app
The twelve factor app
 
High Volume Payments using Mule
High Volume Payments using MuleHigh Volume Payments using Mule
High Volume Payments using Mule
 
Security of Oracle EBS - How I can Protect my System (UKOUG APPS 18 edition)
Security of Oracle EBS - How I can Protect my System (UKOUG APPS 18 edition)Security of Oracle EBS - How I can Protect my System (UKOUG APPS 18 edition)
Security of Oracle EBS - How I can Protect my System (UKOUG APPS 18 edition)
 
Performance management
Performance managementPerformance management
Performance management
 
Running Airflow Workflows as ETL Processes on Hadoop
Running Airflow Workflows as ETL Processes on HadoopRunning Airflow Workflows as ETL Processes on Hadoop
Running Airflow Workflows as ETL Processes on Hadoop
 

Recently uploaded

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 

Recently uploaded (20)

办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 

python_development.pptx

  • 2. Web Development packages • Flask - Backend framework • SQLAlchemy - ORM • Celery - Task Queue • Pydantic - Validation • dashboard-support-py - Internal Authentication • uWSGI - WSGI complaint web server • tensorflow_model_server - Deploy models in production • Redis - In-memory key–value database • docker - containerization
  • 3. Flaskname inspired from bottle • WSGI compliant microframework, with no batteries included. Gives developer utmost flexibility. • Not suitable for large codebases where MVC structure makes organization easier. • Includes development server for quick development, that should not be used in production • Does not come with ORM and is most commonly used with SQLAlchemy. • Good Practices: • Use application factory and blueprints for organizing feature level code. • Use existing exception classes and status code instead of rewriting them again. • Add logging to all exceptions. • Application and Request Contexts • Application context and request contexts are pushed in order for each request. • Flask has several thread-local variables like current_app(proxy to application context), request(proxy to request context) and g which hold reference to any object like database_connection throughout the entire request-response cycle. • Contexts should always be pushed before accessing these current_app and request variables or you would end up with common RuntimeError: Working outside of request context.
  • 4. Celery • Commonly used task queue library in python with support for many brokers RabbitMQ, Redis, SQS etc., • Task names with arguments are serialized (supports json, pickle) and sent over the network to broker • Support for multiple execution pools, like prefork (multiprocessing), solo (single process), eventlet, gevent • Has signal handling mechanisms for SIGTERM • Redis as a Broker • Task messages concerning a queue are stored as list. Number of pending tasks can be found by issuing LLEN from redis-cli or client library. • New tasks are pushed with LPUSH by producer • Tasks are prefetched by workers using BRPOP
  • 5. Celery Good Practices • Keep tasks idempotent as much as possible(retry should always produce same results). • Common exceptions like network errors, should be caught and retried with exponential backoff • Create a subclass of BaseTask and add handlers for task success, failure, return and retries. • Use send_task or signature methods importing of calling task’s apply_async or delay methods. • Use Signals for decoupling application logic with tracking/cleanup logic. Signals are executed either in producer process or worker MainProcess/ForkProcess depending on execution pool • Useful signals include after_task_publish, task_prerun, celeryd_init, worker_process_init • Don’t use result_backend in production(if the process that called it doesn’t wait on its result) for performance improvement. • Good Configuration to start with • worker_prefetch_multiplier = 1 • task_acks_late = True • task_reject_on_worker_lost = False • worker_max_tasks_per_child = 2000 • task_ignore_result = True • task_soft_time_limit = 120 • task_time_limit = 180
  • 6.
  • 7. Deployment • flask • uWSGI • WSGI compliant production grade web server with limited community support. • Has many configuration options and legacy defaults which are difficult to tune for specific use cases. • mod_wsgi with Apache • Model inference • Tensorflow model server • High-performant model server with batching support for better utilization of hardware resources. Exposes grpc and REST APIs natively. Recommended to use gRPC API. • gRPC • Has language agnostic implementation with similar API in different languages • Serializes the request body using protocol buffers resulting in low network payload • Uses faster HTTP/2 protocol underneath, and has its own advantages over HTTP/1.1
  • 8. Profiling • Profile your applications to find where it’s spending time and optimise those areas. • Work by periodically collecting samples of execution point of a process by interrupting the OS. • py-spy is one such profiler specific to python. Produces nice flame graphs and stack traces
  • 9. Docker - PID 1 case • Scaling up/down mechanisms for load balancing should be designed carefully for containers. • Docker sends the SIGTERM signals(handlers inside application defined by application developers) to the running containers for graceful shutdowns while scaling down. If the container does not shutdown in the predefined duration after cleaning up (10-30 seconds), docker sends SIGKILL. • Docker runs the process defined in ENTRYPOINT with PID 1 and passes all the signals to this process. This has certain limitations: • If the ENTRYPOINT is defined as /bin/bash -c celery -A celery_app worker or entrypoint.sh, shell gets PID 1 with celery as its child process(different PID). • Shell behaves differently when it is run as init process. It ignores SIGTERM/SIGINT signals. • So the child process (celery) doesn’t receive any signal and continues to pick more tasks from the broker. Finally, when the SIGKILL is sent, worker exits instantaneously leading in process failures. • Solution: • Use exec to run the command inside entrypoint.sh like exec celery -A celery_app worker inside entrypoint.sh This replaces the bash process and takes PID 1. • If required, lightweight init system like tini (which takes PID 1) can also be used on top of this as they have signal passing capabilities to child processes.
  • 10. References • https://hynek.me/articles/docker-signals/ • https://docs.celeryq.dev/en/stable/userguide/signals.html • https://blog.wolt.com/engineering/2021/09/15/5-tips-for-writing-production-ready-celery-tasks/ • https://www.youtube.com/watch?v=kUz2zjkKxFg • https://www.youtube.com/watch?v=IvsANO0qZEg