Azure Database for PostgreSQL flexible server Slow with Django

Question:

Am using Django to connect to Azure Database for PostgreSQL flexible server but it’s very slow, below are the specs of the server :

Compute + storage

Pricing tier
Memory Optimized
Compute size
Standard_E4s_v3 (4 vCores, 32 GiB memory, 6400 max iops)
Storage
32 GiB

High Availability :

High availability
Enabled
High availability mode
ZoneRedundant
Availability zone
2
Standby availability zone
1

Specs

specs

As you can see above, the specs are high, but the performance isn’t better, in postman when I was hitting to get data it took 34.5 seconds, this is way too much to wait.

In my Django code, I tried my best to optimize the queries, and on Heroku, it was super fast, however here on Azure it’s extremely slow, what could be done to improve the speed of the server?

For more information on Django this is the view.py of the endpoint:

@method_decorator(cache_page(60 * 60 * 4), name='get')
@method_decorator(vary_on_cookie, name='get')
class PostList(generics.ListCreateAPIView):
    """Blog post lists"""
    queryset = Post.objects.filter(status=APPROVED).select_related(
        "owner", "grade_level", "feedback").prefetch_related(
        "bookmarks", "likes", "comments",
        "tags", "tags__following").prefetch_related("address_views")
    serializer_class = serializers.PostSerializer
    authentication_classes = (JWTAuthentication,)
    permission_classes = (PostsProtectOrReadOnly, IsMentorOnly)

    def filter_queryset(self, queryset):
        ordering = self.request.GET.get("order_by", None)
        author = self.request.GET.get("author", None)
        search = self.request.GET.get("search", None)
        tag = self.request.GET.get("tag", None)

        # filter queryset with filter_backends  
        queryset = super().filter_queryset(queryset)
        if ordering == 'blog_views':
            queryset = queryset.annotate(
                address_views_count=Count('address_views')).order_by(
                '-address_views_count')

        if author:
            queryset = queryset.filter(owner__email=author).select_related(
                "owner", "grade_level", "feedback").prefetch_related(
                "bookmarks", "likes", "comments", "tags",
                "tags__following").prefetch_related("address_views")

        if tag:
            queryset = queryset.filter(
                tags__name__icontains=tag).select_related(
                "owner", "grade_level", "feedback").prefetch_related(
                "bookmarks", "likes", "comments", "tags",
                "tags__following").prefetch_related("address_views")

        if search:
            queryset = queryset.annotate(
                rank=SearchRank(SearchVector('title', 'body', 'description'),
                                SearchQuery(search))).filter(
                rank__gte=SEARCH_VALUE).order_by('-rank')

        return queryset

Then is my serializer.py :

class PostSerializer(SoftDeletionSerializer):
    """Post Serializer"""
    owner = UserProfile(read_only=True)
    tags = TagSerializer(many=True)
    comments = CommentSerializer(many=True, read_only=True)
    slug = serializers.SlugField(read_only=True)
    grade_level = GradeClassSerializer(many=False)

    class Meta:
        model = Post
        fields = ('uuid', 'id', 'title', 'body', 'owner', 'slug', 'grade_level',
                  'comments', 'tags', 'description', 'image',
                  'created', 'modified', 'blog_views', 'blog_likes',
                  'blog_bookmarks', 'status',
                  'read_time', 'is_featured',)
        readonly = ('id', 'status',) + SoftDeletionSerializer.Meta.fields

    def to_representation(self, instance):
        """Overwrite to serialize extra fields in the response."""
        representation = super(PostSerializer, self).to_representation(instance)
        representation['has_bookmarked'] = self.has_bookmarked(instance)
        representation['has_liked'] = self.has_liked(instance)
        return representation

    def has_liked(self, instance):
        return self.context['request'].user in list(instance.likes.all())

    def has_bookmarked(self, instance):
        return self.context['request'].user in list(instance.bookmarks.all())

In my settings.py, I don’t have unused middleware or apps, I cleaned it up, and I think the issue is on the database, not the code.

What could improve the speed of Azure Database for PostgreSQL flexible server?

Answers:

This latency issue could be because of region differences in Azure. You should have the backend-service, that communicates with the database, in the same region.

Answered By: Andy Ishak
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.