SlideShare a Scribd company logo
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 shells
Anthony D Hendricks
 
12 Factor App Methodology
12 Factor App Methodology12 Factor App Methodology
12 Factor App Methodology
laeshin 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 Summit
Miguel Zuniga
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
Smitha Padmanabhan
 
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
SergioBruno21
 
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
Shikha 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 sangam17
Vinay 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-2015
Pavel Chunyayev
 
Frameworkless CLI app in PHP
Frameworkless CLI app in PHPFrameworkless CLI app in PHP
Frameworkless CLI app in PHP
Max Bodnar
 
Service-Level Objective for Serverless Applications
Service-Level Objective for Serverless ApplicationsService-Level Objective for Serverless Applications
Service-Level Objective for Serverless Applications
alekn
 
Docker Swarm and Traefik 2.0
Docker Swarm and Traefik 2.0Docker Swarm and Traefik 2.0
Docker Swarm and Traefik 2.0
Jakub Hajek
 
Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502
kaziul Islam Bulbul
 
The twelve factor app
The twelve factor appThe twelve factor app
The twelve factor app
Inthra onsap
 
High Volume Payments using Mule
High Volume Payments using MuleHigh Volume Payments using Mule
High Volume Payments using Mule
Adhish 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 management
Alan 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 Hadoop
clairvoyantllc
 

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

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 

Recently uploaded (20)

BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 

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