Prevent race-condition in RESTful api in certain scenario - rest

I'm currently developing an online course system where students can choose any course and enroll to it. The course will be held one-to-one principle so student will choose a certain date for the course and on that date, there will be an online video meeting with the instructor. Only one instructor and one student for each course session.
Typical use-case flow is:
Student press "Enroll" button and proceeds to the next page.
On this page, student chooses the course date from the calendar (only from available dates) and proceeds to checkout page.
On checkout page, student enters his/her card details and certain amount charged from student.
A race condition may occur in this scenario (let's say there are only 2 users and 1 instructor):
User1 chooses date from the calendar and proceeds to the checkout page.
Meanwhile User2 also chooses exactly same date and proceeds to checkout page.
User2 enters card details faster that User1 and reserves that date.
User1 enters card details and system charges both students and BINGO (there are two students for the same date).
I don't want to check date availability before payment so I think It'll give a bad user experience so the User must go to the previous step again and choose another date. Even this could happen infinitely :)
Any ideas will be welcomed.
Also, I can change the current enrollment flow to protect security.

The reference you want to review is Pat Helland 2007: Memories, Guesses and Apologies
You've got a distributed system, and remote clients are looking at local copies of your data that may be out of date. So your protocol needs to recognize that you will be receiving messages about decisions based on stale data, and have explicit handling for the contingency that the desired outcome of the decision is not currently available.
The REST part is "just" providing the correct affordances for your protocol.
One possible change to your protocol that may help is to introduce the idea of a provisional hold; Alice has a provisional hold on the time slot, and therefore when Bob asks the slot is unavailable, but it might become available later if Alice declines to exercise the option.
(This doesn't eliminate the race condition, of course, it just moves it around).
A common protocol solution here is overbooking - you accept both claims on the time slot, and then clean up the mess later.
Commercial airlines do this sort of thing all the time; they want to maximize their profit per flight, which means selling more tickets than there are seats on the plane. They can do this, because enough travelers change their plans later that there is an effective surplus.
But sometimes, too many paying customers show up for the same flight, and then the contingency plans come out -- standby passengers are deferred, ticketed customers are offered compensation packages for changing their plans, and so on.
You probably need contingency protocols anyway (what happens if the instructor has to cancel the appointment, for example because of illness); the race condition during booking is just one more contingency protocol to add to the run book.
Having established what the contingency protocol should be, you then have a second question to explore: what parts of that protocol should be automated. If conflicts are rare, it may make sense to escalate the problem to a human being to solve, rather than doing so in code. Sometimes the right answer is for the machine to stay out of the way.

I want to implement double-check mechanism so:
When User1 proceeds to calendar page it will create a persistent connection with the server (SSE or WebSocket). And available dates will be shown on real-time. So when User1 selects any date and proceeds to checkout an event will be published and that date will be marked as BLOCKED until the payment done.
When User1 enters his card details and clicks Pay button the system will check again if that date is really reserved by User1.
If payment is successful this date will be updated from BLOCKED to RESERVED.
BUT taking into account that this is a REST API with React client, all of the endpoints will be visible to anyone. So an attacker could make a simple brute-force to BLOCK all available dates for the course.

Related

Google analytics and different domain tracking

I asked this question directly to the Google Analytics community with absolutely no answer.
The question is as follow:
I have a AI based site, which give a customer a specific aid to select the right product he/she want to buy. The front ed application is React/js based.
My site is usually a small icon on a merchant site, and the user, while he/she is navigating the merchant site, can decide to recall clicking on a specific icon.
Then my site opens and help the user to select the right product(s) belonging to the merchant site. The product are choosen and then clicked to be added to the merchant cart.
Of course, there is a written agreement between the merchant and I to be signed, and some changes to the merchant site to incorporate my clickable icon: I'd like to pass a piece of code to the merchant including the icon and all the code needed to implement this kind of application.
So, given that the merchant call my site passing a specific transaction related token and the customer info (if any) when the user click on my icon, how can I:
directly add one or more items into the merchant cart
track the action made by the user after he/she leave me site and return to the merchant one to conclude the journey with a payment, so I can later invoice the merchant for the right commission
track if the user remove some (or all the) item from the cart, so I have less to nothing commissions to invoice.
I tried to follow the instruction given by google, but they are a mess, and I wasn't able to reach any conclusion.
Any help will be really appreciated.
Adding items to the merchant's cart is possible using some live API that the client would extend, but the easiest way to do it would be just using the window.postMessage(). So, I would suggest having your button implemented as a simple iframe. That will make it possible for you to send messages to the parent page from that button. The parent page, however, has to be ready to listen to those messages and add to cart whatever ids you specify. So the client devs will have to do some implementation for this to work.
Well, no, this is a bit too much to ask for. You can ask the merchant to share that data with you so that you could improve your algos (tune them for the client) and, therefore, improve the merchant's conversion rates (which is a win-win scenario), but the merchant would have to actively either implement parallel tracking to your instance of analytics (install your pixel, if you're willing to develop one), or share their own data with you.
That's what a lot of very similar services do. Let's say, Facebook. Facebook sells traffic. When you buy traffic, you generally don't want to pay for irrelevant/badly converting tracking, so you're implementing so-called facebook pixel. Facebook doesn't do this implementation. Client's developers/implementation experts implement it and trigger various events through it, making it send signals to the FB endoint, indicating which client this is from, for which campaign, what the action is page load, purchase, add to cart... Just take a quick glance at FB documentation: https://www.facebook.com/business/help/402791146561655?id=1205376682832142
Facebook is just an example. There are many-many services that do similar pixels. It may be not about selling traffic, it may be about adjusting site look and feel based on AI, or generating discounts and customizing conversion funnels, or even simpler stuff like feedback chat performance and suggestions modules. All these and more exist as third parties and pretty much all of the established ones use pixels for tracking.
If you don't want to spend time at the moment to make your own tracking logic, then implementing a parallel GA tracking will be a pain for you (for your clients, actually). Instead, it would be easier to enrich their data with your products. Let's say, have them implement a product-level custom dimension that would "paint" products added to cart by you and share the data with you.
Note that a client who goes for it must be a very loyal client since analytics data is normally treated as sensitive and is not readily shared with third parties, not mentioning the implementation of a custom dimension (or the using the expensive product parameters) just for a third party to count their conversions. Yes, it has to be a good friend that allows this.
Finally, you could ask them installing your GTM instance or giving you access to theirs, but that would effectively give you the power to execute arbitrary code on any of their page. I would never give a third party that power.
Tl;Dr: I would suggest making your own very simple pixel. Even though it sounds now like a lot of work, it will worth it if the project itself has real potential to be useful for ecommerce.
Exactly the same as 2.

Coupon discount once added not getting flushed once after completing the order

In ATG once used coupon not getting disassociated after the completion of the order. If without ending the session I am continuing same discount is reflected in cart without using the coupon.
Coupon is just a delivery mechanism of a promotion. All that a coupon functionality does is to allow user to enter it and identify the promotion associated with the coupon. It depends on the promotion flags and rules to determine whether this promotion is only for this order or can it be used multiple times or stays on forever.
In your case, you may have a promotion with "Max Uses per Customer" more than 1. This will allow for the customer to get this promotion in his profile and every time he/she comes back it will be available for use.
Check this out for information - http://docs.oracle.com/cd/E24152_01/Platform.10-1/ATGMerchandisingUserGuide/html/s1404availabilitycouponstab01.html
If you feel that the promotion is defined correctly, look at the activePromotions property on the profile to find why it continues to remain active. Here is more information on that - http://docs.oracle.com/cd/E24152_01/Platform.10-1/ATGCommStoreGuide/html/s0502howpromotionswork01.html

Implementing PayPal discounts - what if the user cancels?

Alright, I got my Paypal shopping cart set up and working, now I'd like to be able to add discount coupons.
I know I can simply implement the 'discount_amount_cart' variable in my form, but I'm still a little lost when it comes to handling the deactivation of a coupon code.
Let's say A activates the code. Now in my database it will be marked as 'reserved', meaning no one else can use it. Once A completes his transaction, the IPN will mark the code as 'used' and it becomes useless.
But what if A decides to activate the code, but never actually buys anything on my website?
I'm using the $_SESSION variable to save my shopping cart, so once the user returns to my website, the code might still be shown as activated for him. When exactly would I mark it back as 'not reserved & not used' in my database?
I could do this based on time, but this doesn't really feel safe either. Let's say the user puts everything into his basket, goes to Paypal, waits for an hour and then decides to finish his checkout. The discount would still be activated, but in the meantime, it could've already been 'unreserved' in the database and used by another person!?
How would I go about this?
Thanks in advance!
IMHO, this has little to do with PayPal and more about your business rules. If your coupon is single use (globally), then you will be faced with the same issue regardless of any payment flow.
Simply putting it in "cart" and/or any event where a user "activates" said coupon, then just navigating elsewhere in your site, doesn't do anything, [whatever], creates that lag
it could be Paypal, Amazon, your own gateway - it really doesn't matter...but there will be a lag between activation and payment (beyond your control)
I think it's just best to be explicit with your customers and handle it appropriately technically (based on what that explicit messaging is).
You'll see some implementation of "timed purchase" at ticketing sites (e.g. buying a ticket to a game, movie, etc.) - they will have a "timer" for the user to do something (otherwise, the "reservation" is lost).
Hth...
Put an expiry date on coupon use - such as must be used within 10 days of activation. It gives the user urgency to use the coupon and gives you a timeframe to invalidate it.

Analysis class diagram - associating classes

New user so I can't post images. Image link provided below:
http://i.stack.imgur.com/EXf0G.jpg
This is for a walk-in booking system not an online reservation system.
Normal Booking scenario:
User/Member gives information to receptionist. Users can book up to a month in-advance.
Receptionist searches user/member info. Receptionist must be logged in to search user/member or make a booking.
if details are found the booking continues as normal, if not user details are added to the users file.
Booking time/date/type is then checked for availability. If available then a booking is made.
Extra:
There are two types of staff account 'normal-user' (Receptionist) and 'admin' (Manager).
Manager can reset staff account passwords and create new staff accounts.
Manager can edit session details on the timetable (time, date, type) etc. Do i need a timetable class here??
In order to answer that, we would need a much more developed specification.
I would suggest you develop with what you have, meeting only the minimum requirements for each iteration. Then, if you find your users need a timetable of some sort, then add it at that point.
In general, don't add more complexity than you need until you know you need it. The more moving parts a system has, the harder it is to maintain and use and to put together in the first place. Get the application up and functioning and in the users' hands. Until you get real feedback from them, you are just taking stabs in the dark. Let the users' tell you what they need and want.

It is possible to manage users/identities in a data store that exhibits eventual consistency?

Is it possible to create/store user accounts in a data store that exhibits eventual consistency?
It seems impossible to manage account creation without a heap of architectural complexity to avoid situations where two account with the same UID (e.g. email address) can occur?
Do users of eventual consistency stores use a separate consistent DB as an identity store, or are there solutions/patterns that I should be exploring?
Thanks in advance,
Jamie
It is possible to do use management in an eventually consistent data store. We do it. It works under the following assumptions:
Conflicts shouldn't happen and when they do there's a clear path to conflict resolution. If the account ID is a person's email address, then if two separate people try to register under the same email there's a bigger problem here. What we do in this case is block both new accounts as soon as the conflict is discovered and send an email to the address in conflict explaining to the user that there's an issue (possible fraud). You can either ask the user to reset to the account or ask them to contact support.
Repeated access by the same user within the timeframe in which the data is inconsistent go to the same replica. For instance, if a person just registered and the next request is a login, you must validate that login against the data replica where the new registration details exist. So if the eventual consistency is due to multiple data centers in different geographic locations and under normal conditions a request goes to the closest data center geographically, you're OK.
There are some edge cases, such as if a user registered against one data center, then that center crashed, and now the user cannot login even though he still can see the application - served from some other data center. You can calculate the expected frequency of this case based on your number of daily new users and average data center downtime. Then decide whether it's worth worrying about one user in a (million/billion/whatever your number is) having a problem and possibly contacting support. I faced the same decision not long ago and decided that from a cost-benefit perspective the answer is no.