How does shopify determine from where a user is ordering?

I’m facing some issues related to automatic multi-location inventory tracking.

Suppose I’ve ‘X’ product in location ‘A’ and ‘B’. Location ‘A’ has 5 of that item and ‘B’ has 0 of that item.
But when a customer tries adding this product to cart from location ‘B’ - in the background I’m checking for the available quantity and getting 5. So I’m processing to add it to cart using the cart api but getting error saying ‘out of stock’.

So I was wondering how does Shopify determine which inventory to select for a customer and how can I get that data?