xoron

xoron

Employee Booking: Using ETS for Concurrent Requests

My application facilitates online consultations between clients and employees across various companies.

  • Employees: Belong to specific companies and can be in one of four states: idle, offline, busy, or init (initializing a session).
  • Clients: Request sessions on specific topics.
  • Booking Process:
    1. Clients send booking requests via websockets to a company.
    2. The backend searches for an idle employee within that company.
    3. If found, chnage the employee status to init the backend sends a request to the employee to accept or reject the session.
    4. If rejected, the backend searches for another idle employee within the same company and repeats the process.
    5. Upon acceptance, the employee’s status is changed to busy. On rejection, it reverts to idle.
    6. Clients can only send booking requests if idle employees are available within the company.

Technical Implementation:

I’m using an ETS table to store employee data.

Challenges:

  1. Efficient Data Access: What is the optimal key structure for the ETS table to quickly locate idle employees within a specific company?
  • Should I use a tuple key {company_id, employee_id} and rely on match operations? because i only have company id so i do use match with only company id.
  • Should I store a list of employees under each company_id key?
  • Would creating separate ETS tables per company be more efficient?
  • Are there indexing strategies to optimize lookups?
  1. Concurrency and Scalability: How can I handle a high volume of concurrent client requests without encountering bottlenecks or race conditions?
  • Is a single process sufficient for ETS manipulation and access?
  • If using multiple processes, what locking mechanisms should I implement to ensure data consistency?Should i use shards
  • Are there alternative approaches to improve scalability without compromising data integrity?

Key Concerns:

  • Fast Lookup: I need to find idle employees quickly (ideally O(1) time complexity).
  • Scalability: The system should handle thousands of concurrent client requests.
  • Data Consistency: Ensure correct employee status updates and avoid race conditions.

I would greatly appreciate any insights, suggestions, or best practices to address these challenges and design a robust, scalable solution for managing employee bookings.

Most Liked

al2o3cr

al2o3cr

The central thing to think about when designing with ETS is “what operations does this need to support?”. There are specific things that ETS can do very efficiently, so you want to structure your code to align with those.

For instance:

ordered_set tables have an efficient next operation for a given key, even if the specific key is not present in the table.

So imagine an ETS table with the structure:

{{company_id, timestamp_ms}, employee_id}

where an employee “becoming available” inserts a tuple.

The scheduler can ask :ets.next(some_table, {company_id, 0}) - and get the tuple with a matching company_id and the lowest timestamp.

There are some corner-cases to watch out for:

  • if there are NO tuples with that company_id, next will return one from the next company. The scheduler could either deal with this by inserting a sentinel “no more employees” value, or by checking the result.
  • two employees that become available at exactly the same millisecond will cause one of their inserts to fail. Increasing the timestamp precision to microseconds would reduce this chance, or the scheduler could retry.
  • since employee_id isn’t part of the key, an employee could have multiple tuples with different timestamps. This may be a feature, but if it isn’t see below.

The other thing is to use multiple ETS tables to handle different questions. For instance, the “employee can have multiple entries” case, you might have an auxiliary ordered_set table like :

{{company_id, employee_id}, timestamp_ms}

The scheduler would attempt to insert into this table first when recording an employee’s availability.

The above table can also answer useful-sounding questions like:

  • “is this company’s employee available?” (:ets.member)
  • “since when has this company’s employee been available?” (:ets.lookup_element)
  • “what employees are available for this company?” (:ets.next etc)
D4no0

D4no0

Let me give you my 5 cents on the problem you are trying to solve: if you don’t have a hard requirement for response time, then as others mentioned above, use a database.

There are multiple reasons why the ETS solution is harder to maintain, some of them:

  • all the data stored in ETS tables will vanish when you restart the server or redeploy (with exception if you are doing hot-code reloading, but that in itself a hard thing to get right);
  • you can have potential problems as you mentioned with the inbox overflow if you don’t know exactly what you are doing;
  • the complexity of having persistence will most likely outweigh the small performance gain you will get from storing the data in memory.

What I would personally do, is try implementing a prototype using ecto + sqlite, check response times when the throughput is to your expected maximum and decide whether that is a good or bad solution.

You can also later add a caching layer in ETS by using one of available caching libraries like cachex (this library also handles message overflows for you). Having the source of truth in the database will save you a lot of trouble and will offer you a structured way to store your data.

dimitarvp

dimitarvp

Yes, Postgres.

Your speed concerns seem overblown. Are you sure you’re not over-optimizing for a problem that you’ll never have? Do you have hard requirements to respond within 1ms or less?

dimitarvp

dimitarvp

Why is database not your go-to solution?

dimitarvp

dimitarvp

Look up how cachex does transactions in its source code. That could potentially solve both your performance and race condition worries at the same time.

But as @D4no0 said, I’d use cachex together with SQLite. It will live inside the OS process of your app so any extra latency will be extremely minimal.

Where Next?

Popular in Questions Top

bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New

Other popular topics Top

yurko
Here are few pieces of (common) Linux knowledge that we use for reasonably small one server apps. We use Ubuntu but this should work for ...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement