Sync VS Async
Introduction
By using DSG you can use both sync and async mode for gRPC. But sync mode is deprecated as it can lead to issue with stream and poor performance.
Working in sync or async mode makes almost no difference to the way you develop your APIs. However, there are important differences in the deeper workings of your API.
Differences
The main difference is that async mode will allow you to handle many more requests in some cases. Particularly if you’re using streaming, where using sync mode can block the whole server.
Mixins
All mixins classes inherit from the same base class django_socio_grpc.grpc_actions.actions.GRPCActionMixin.
Async Class |
Sync class |
|---|---|
|
Services
All services classes inherit from the same base class django_socio_grpc.generics.GenericService.
Async Class |
Sync class |
|---|---|
|
Async ready methods
Since Django 4.1, Django can run Views asynchronously. Check Django documentation for more information.
If you use version of Django < 4.1 or for all django ORM methods not supported, you can use asgiref to wrap sync methods in async context.
from asgiref.sync import sync_to_async from my_app.models import MyModel async def aget(self, pk): return await sync_to_async(MyModel.objects.get)(pk=pk)
In DSG we provide a lot of async ready methods.
Servicesaget_objectaget_querysetaget_serializer
Sync support
If you want to use the sync mode, you should know that we are thinking about droping sync support from version 1.0.0 of DSG.