What is the best way to load two different queries? (Elixir Task? Or etc.)

Hi, I have a notification part on my project which has 2 schema tables:

  1. notifs = notifications is sent by system or moderator users
  2. user_notif_status = read or skipped notifications of user.

Imagine in this forum you have a profile picture in the top of the right side that shows you how many notifications you have 3 or 20, it counts them for you. If you clicked on it, you can see your last 10 notifications with status, you have read or not!

Then, if I make a query for loading last 10 queries, I do like this:

from(n in Notifs, left_join: s in assoc(n, :user_notif_status))

It is okay for now, but I have a problem when I want to count all the unread notification. I think these are separate queries and different. I could not use subquery because it loads my counter every record and I don’t want it, I just want to load counter one time.

Furthermore, I have 2 solutions on my mind:

  1. use elixir task to send 2 queries and show it to my user.
  2. load 2 different queries.

Please suggest me what to do that is better for load time when I have a big database on my projects.


If your first query is fetching both read and unread notifications, you could pass the results into Enum.count/2

I am using paginate and do not load all the records parameters, I just load last 10

  • count all records on my db
  • load last 10 notifications

see these images

Screen Shot 1400-07-15 at 19.38.17

Screen Shot 1400-07-15 at 19.42.39

Ah. I think it’s fine to use Task for multiple async queries, since Ecto does this under the hood also. But since the count query must check the entire table, there is potentially a faster way: adding an unread_count column for each user, which gets updated during transactions where a notification is created, read, or skipped. Since it removes work from each read, but adds work to each write, this would be optimal for situations where page loads are more common than new notifications.

1 Like