For large-scale recommendation systems like YouTube's feed, a multi-stage architecture is essential to balance accuracy, latency, and scale constraints. The system employs two main stages: a candidate generation stage that prioritizes scale and latency by filtering billions of items down to thousands using approximate nearest neighbors and embeddings, followed by a ranker stage that prioritizes accuracy on the smaller candidate pool. Labels are derived from user interactions (likes, watch time, end-screen clicks) with careful handling of class imbalance through temporal splits and negative sampling. Real-time updates use lightweight models to adapt to immediate user intent while maintaining long-term embedding stability through periodic retraining. Deployment follows AB testing with continuous monitoring and retraining every few hours to maintain model freshness.
ML System Design Mock Interview: YouTube Feed Recommendations
Added:wait a minute no way you can do all that in like 30 minutes challenge accepted no script no multiple takes which is going to go beginning till end me solving one question in 30 minutes for ML system design interview so the question we're going to tackle today is design a feed for YouTube recommendations YouTube has billions of users daily and it doesn't matter if it's 500 million or three billion and you know each one of them most of them probably don't post but they're probably a good 100 million or more uh order of magnitude New pieces of content posted to YouTube every day we're going to ignore the shorts for the purposes of this uh and just stay with long uh long form content so we got a boatload of those also the recommendations on you YouTube unlike some other social networks can go back quite a while it's still relevant to me to get recommended things from a few years back and so yeah there's there's going to be some cut off we can think about it in terms of exponential decay as it gets further and further away and we could model that or we can just say we're going to cut it off at a certain point in time what I need to predict at the end of the day is what I need to produce rather is a feed of about let's say a couple of hundred videos that have the first one of which is probably the most relevant and then they decrease in relevancy a little bit but still remain pretty relevant to the user does that sound reasonable okay thank you Mr interviewer or Mrs interviewer okay so if that's what I'm predicting I I would need to know so I know the scale now but the the other thing I would like to know is uh the latency so there is this property of the recommender systems that or really anyl models that you know you could have latency you could have so by that I mean tight latency um you could have scale and you can have accuracy and any two of the three you're welcome to have but I think the problem here is that this this is business critical so we have to have accuracy latency needs to be quite tight because if you've ever sat in front of your computer for a couple of seconds while the page loaded that's not acceptable it's got to be subsecond probably 100 milliseconds or so again order of magnitude and then scale we have a tremendous scale so what I want to do do is I want to rank all the posts but unfortunately I can't do that easily here so we're going to need to talk a little bit about how to handle that the other thing is the post I'm just going to assume the actual item I guess is a video some description maybe a thumbnail and a title so let's just for Simplicity assume that th those four pieces make up an item and then let's assume that we have a system in place today because somehow we are going concerned so there definitely is some system in place even if it's just random but we can compare against that to see how well we're doing and what we're after his engagement right so likes I'm going to say that having watched maybe 30% of the video is maybe um an engagement point maybe we have a couple of those I don't really want that to be a continuous VAR able I would rather have it be watch you know 10% watch 30% watch 50% watch the whole thing something like that all right I think we're ready to jump into the rest of this uh does this sound like I understand the question are there any nuances that I might have missed okay thank you very much so I just want to go through and let you know kind of how I'm going to think this through to give you a mental mind map of what h is going to happen and just to kind of align on this right so first I want to go through big picture architecture of this and then we're going to go into some data considerations followed by modeling if only a good spell and Then followed by deployment so deployment to me is everything that happens after you have a model that you're quite comfortable with so if that's okay with you let's proceed and uh uh yeah I'll cover things in this order so for big picture what I really want to do is I want to make sure that we're covering this problem that I've identified here right so this guy right here is going to give me some problems here because I have kind of the need for all three so we're probably not going to solve all three of them in a single model and that's okay so oops I'm going to get over to the side here so a user submits a request for this feed I have some service here the service will talk to the service will talk to uh the machine learning model and and what it's probably going to first ask for is it's going to talk to service uh and this is going to be our candidate generation model so what I want to do in order to solve the triangle dilemma that I showed is I want to split this up into multiple stages so the candidate generation stage in particular really only cares about the scale and the latency we are going to have some false positives that this identifies and that's okay uh we're going to optimize it to identify as many true positives as we can and we're going to go from you know maybe a billion or like so like they're billions of posts uh I'll I'll draw that in a minute to maybe a couple of so like the input into this is maybe a billion posts again if only I could spell and the output of this is maybe a few thousand maybe a thousand I don't know order of magnitude right and then I can have another stage which is my ranker so this is going to this is what's going to determine the relative relevance to uh the user and this ranker is going to go from thousands to thousands because that's a ranker rankers don't kick things out but yeah so here we have a Rinker but this thousand is now arranged in order and then I'm going to have some non a m system I'm just going to represent it with the oval for no real reason and so this is like business rules so this is you know the most basic version of this is we can just cut off that thousand down to a couple hundred that we need uh but we probably want to take care of diversity like if all of them are videos from me um that's terrific we should keep that but if all of them are videos from I don't know somebody else then we only need like one video from that Creator um in the feed and uh yeah so business rules can also enforce a couple of other things here um and actually now that I think about it we probably want to have business rules kind of everywhere so even here we might want to start enforcing some diversity maybe not uh but it's good to have some business rules here and here we can uh sorry right here we could have business rules for like let's say the user is 18 years old or younger we don't want to surface them content that's like 21 plus let's say the user has never watched a YouTube video in Japanese we want to maybe not serve them content in Japanese right so this this just helps us basically things that we already know we can eliminate and uh for anything else you know we pass that to the candidate generation so there is another path here and there's another type of user or another user who generates the post and so user generates a post I apologize uh so post that also goes through some sort of service but um we don't care about that that much right now what matters is that the moment the post is generated I don't want to take up any of my precious time once we get to the scandid generation St stage I know or post as a video in this case I guess uh so I don't want to take any of my precious time here I want to encoded and store it as an embedding here uh at generation time I guess one thing I didn't ask that I uh didn't clarify that I probably should have is I'm assuming that it's okay that a video is not recommended right away that there's some encoding step here on YouTube it takes a little minute uh for it to go live is that a reasonable assumption okay so yeah so this gets stored as an embedding and it's from those embeddings that we start our our um exploration here the user also has activity that also goes into offline path um it could be either user but um well you know let's not do that let's uh let's do another user and now like there is activity right so like interacting with interacting with different videos like doing all sorts of stuff and I think we're going to store user embedding as well so both of these would live like in an embedding store or basically Vector store so there's some Vector store here and these are not static things so maybe we recalculate them every once in a while maybe once a day or so I'll talk a little bit more about how we deal with them in real time but overall I think for the system we do that we just recalculate them every once in a while on a Cron job and then I'm going to leave kind of that part of the system right here it's in the real time portion so this separates the real time below it from [Music] the from things that happened uh before the feed was recommended we'll talk about this box when I talk about data and this box is meant to like it's some sort of a so like real time update the idea here is that if I go on YouTube specifically to find a way to fix my car and it's 1998 Toyota Corolla or something and I watch a bunch of those videos uh the algorithm should probably adapt quicker than we can retrain these embeddings and so we want to make sure that we capture that signal so there's a there's something we need to do there but but we'll get there in a minute and then from those business rules in the end we basically generate about a th000 posts oops and those posts go back to the service and the service communicates back to the user so yeah there's not a way to do a two-way Arrow here sadly so goes back to the user okay so and this round trip should be really fast so again in the first stage in the candidate generation stage we're prioritizing uh for scale and latency and in the second stage we're prioritizing for accuracy and latency but at that point the scale is not too big just a few thousand and here we can say you know we're getting hundreds back to the user yeah how does that look is that um is that similar to what you're thinking okay good good okay so the good news is we have two of these embeddings calculated entirely offline to the system so they don't lead into our latency budget at all so let's talk a little bit about data considerations so the first thing that I want to talk about with data considerations is um our labels U so obviously hard to do machine learning without any labels so where do our labels come from well we already talked about how we have a system currently and we talked about how interaction is what we're trying to prioritize and so if interaction is what we're trying to prioritize these these could be essentially likes if you don't know about likes on YouTube take a look at the button below it has a thumb up and uh if you're still here at this point why not put a like on this video might help out the algorithm maybe watch time right so we talked about that bucket it there there are probably a few other signals like when you get to an end screen did you click on the thing on the end screen are you still watching that Creator did you click a follow maybe um which like if you're not following this awesome mle path guy you should be yeah so there's a whole bunch of signals here and I would probably do some classification problem here so this is binary multi-label classification the reason I like to have multi-label so I probably would train uh for each of those labels and then I would train overall for engagement somehow but even training for each of those labels would already give me a lot and if my product manager comes to me tomorrow and says you know what what we've decided is that we really need to prioritize likes then I can very easily tune the system um so those are my labels so those are my positive la labels my negative labels are a little bit trickier here so the trick is that you know obviously the really bad answer would be to say anything that the user hasn't clicked on they don't like well that's not exactly true because they weren't even they didn't even see most of that content so a little bit better is to say anything that appeared in their feed but they didn't click on but I think better yet is if we go through the chronological feed so one two three four right like let's say we have a very simple feed with four videos suggested the user clicked on one that's a clear positive sign the user didn't click on two we're going to count that as a negative the user clicked on three so we're going to count that as a positive the user didn't click on four or anything below that well that means I don't know anything about number four and so I probably wouldn't include that into my labels at all or I would mark it as a separate class and uh not mark it as a negative so the downside to that is we're clearly operating with a lot less data the upside is that the data that we're operating on is a lot better the other upside is that this is a highly imbalanced problem even if I only go off of this this is still probably imbalanced at least 10 to one because most of the things on your feed you're never going to click on but 10 to1 imbalance is a lot easier to deal with in machine learning than like a billion to one imbalance so if there are billions and billions of pieces of content you've only interacted with 10 of them that is actually pretty hard to deal with so we could do some subsampling there or some negative sampling or whatever but we might not even have to do that if we go off of a strategy where we only go to the last piece of content you interact with the other consideration here is that the YouTube feed is a square and so there's you know video Here video Here video Here video here and then underneath and so we need to be a little bit culturally aware here for most western cultures I believe the pattern is left to right and then uh up to down and uh but but we have to be aware of like languages like Japanese and Hebrew are read differently and because of that the scanning patterns in those in the cultures that speak those languages uh tend to be a little bit different so that's something we have to keep an eye on so those are my labels now for features the main question is where do we get features and you know here clearly you know videos we have users and we have interactions between them now in a system like this you know first of all you'd probably have 10 20 50 stages I don't you probably won't have 50 but you'd probably have you know 10 mL stages and notice how when I talked about big picture diagram I really focused in on two I think you know for the purposes of time that's probably the best use of our time and also it allows us to demonstrate some Concepts that would be useful to anything else likewise here let's just talk about a couple of features for each section rather than going into a lot of depth does that sound good okay great so so for videos obviously we already have our um you know the four things that I mentioned you know they might have tags and they might have uh like number of likes and number of likes you know you can't do in absolute terms because a video that's been alive for 30 seconds is probably going to get way fewer likes than the same video that's been alive for 100 hours so likes at some time at one hour or whatever the problem with having it be at 1 hour is that EV initially you have to train that embedding was with a nun and then you have to retrain it but that's life that's how we live so uh for tags there are way too many of them to do one hot en coding so I would probably do something like you know embeddings are pretty good and and here you could probably use off-the-shelf embedding or we might want to train our own because hashtags are sometimes a different beast from general purpose language so so probably train our own embedding for the number of likes uh at a certain time so we have two problems here one is while likes are an integer and we can't theoretically put an integer into our model there's a pretty wide distribution of what they could be so I don't want to deal too much with the outlier so I want to standardize it somehow now how to standardize it you could standardize it in a naive Way by shrinking everything down to negative 1 to one there's really no magic to that though right like what we're trying to do is we're trying to just make sure that things are basically on the same scale and for different creators different numbers of likes mean different things so for a Creator like me 500 likes on this video would be amazing for a Creator like Mark Rober 500 likes would be pretty disappointing on any video honestly and so let's maybe standardize this by the number of uh likes and average video gets or the number of followers or the average number of view or the number of views on that video something like that it won't quite be up to one it might get into the tens even that's okay I'm not too worried about it getting into tens I don't want it to get into billions too fast so uh for users you know we can have several features here so age is interesting maybe um and then you know maybe for users we also have a graph of um or we don't even have to have a full graph just like probably first connections uh there's no of connection on YouTube so like follows maybe um and uh this I would also probably encode in an embedding of some sort for age I would bucke tize it uh and then I would represent it with one hot encoding the reason for that is we're in the business of selling ads and ads actually have very strong like age demographics so you usually sell ads to like 18 to 24 year olds or whatever and so there's a finite number of buckets I'm not too worried about uh sparsity so you know we could we could do that and then interaction between them you know this is where a lot of our labels are going to come from so I don't know that um I'm going to cover that much more and then once we have all this data we need to split it somehow and uh I'm going to propose that we do a train Dev test split the reason you need that Dev set in particular is because you don't want to overfit on your uh test set so on the train set you train the model on the dev set you tune hyperparameters and on the test set you only do the evaluation before the model launches to production yeah and uh and for the split itself since the seasonality is uh probably weekly the content that you look for on weekends could be quite different from the content you look for during the week I would say that we need at least two weeks in uh both Dev and uh the evaluation set the test set so that if something is H something funky is happening on Monday we can go and check the other Monday uh and make sure that that's where it's coming from now downside to that is that you miss out on about a month of data in your training set but you know the moment that your model hits production is going to see data it's never seen before anyway uh so you need to be robust to that and uh the reason we need a temp split here is because certain things Trend based on news but then when the news dies down the the kinds of people it attracts are different and also the patterns of interaction are quite different so yeah temporal split here is quite useful and then I just want to go back here real quick uh and talk about kind of in transitioning to the modeling section the real time update piece but before then do you have any questions on what I just cover covered okay great I have a great interviewer they have no questions today it's almost like talking to you or myself all right so for the real time Updates this again is there to solve the problem of I came on the platform to solve a particular thing and so rather than generating all the candidates you now really should be shifting towards whatever I came there for and this is cashed for a short amount of time and so the way that we can do this is we can have a basic MLP that we train with uh the input is like the embedding so for the user it could be the user embedding for the post it could be the post embedding what changed so a vector of what changed and uh the output is a new embedding so basically it's a slightly modified embedding that we had in the first place so it's sequence to sequence learning a basic MLP would do this quite fast I'm not too worried about latency and then we throw it away at the end of the session uh and then next time we just read back from the initial embeddings yeah so that's what I propose and then we retrain those embeddings once a day or on a slightly longer time scale so that you know the one time you went in there to look at washing machines you didn't just ruin your feed forever with washing machines so okay so for modeling uh we basically already have the outline of the two Tower model we have the user Tower and the so two towers uh the user Tower and the uh video Tower the item Tower whatever you want to call it so basically when we have these embeddings right here uh what we do is we take a DOT product or somehow get them into the same space we find a distance measure so this needs to be the distance metric needs to be quite simple because this is something that we want to calculate fast so even cosine similarity would would probably be fine but I don't know like some distance some distance metric that's pretty easy to compute and uh what we do is we look for the videos that are closest to the user in that space so initially we look for like a couple thousand of them for the candidate generation so we can pass them on and then in the Rinker we use something similar but first let me just go back and say how we're going to look for similar things so approximate nearest neighbors is what I would pick we could do nearest neighbors but that takes up more time more resources and uh it's you know we need to go fast here so approximate nearest neighbors is the right uh algorithm here whereas in the ranker you know I would like to use the same basic philosophy and uh and and just do embeddings plus plus Ann but I would probably do something like this real-time update piece here but instead of real-time update I would give it more features so this embedding could be quite simple and then here the embedding could be a little bit more complex so we enrich that embedding and then do the same thing and what that would do is it would also allow us to do distillation back into our candidate generation model so we can train our ranker which is going to be the more advanced model first and then distill the learnings into the candidate generation model this is a class classifier essentially and uh so um and the most important thing is not to miss any true positives so what we're going to do is we're going to pick recall for our metric here and for a loss you know there's there's a modum of imbalance uh here uh I think a log based something a log loss normalized cross entropy maybe normalized cross entropy would deal with the imbalance a little bit better so let's put normalized cross entropy both here and here as our loss metric and then on the Rinker itself we can't use a metric like recall I mean we could but it wouldn't be applicable um so instead I'm choosing between Mr and ndcg Mr is better when you're trying to guess the first answer right and you don't really care about the order beyond that the since we're trying to get an entire feed that's basically correct ndcg is my metric of choice here so that's what I would start with n dcg and uh recall yeah and obviously like if anything goes wrong you monitor them and you adjust but those are starting points here yeah any questions on modeling okay yeah thank you yeah so that gets us a model we have our train and test splits we can yeah and if we train the ranker first and then go for candidate generation then we can use distillation to be a lot more resource efficient okay so how are we going to launch that to production so for production we need to run an AB test we need to Canary deploy this because other deployment possibilities such as uh blue green deployment for example require us to stand up a whole other system to deploy alongside ours and at these scales is just C prohibitive so AB test here works well we don't really have anything that like lives depend on it if we did if it was like unethical to make the wrong choice for example then I would recommend Bandits instead because Bandits can converge to a solution and then start recommending more content from your B system uh than a if B is truly better but here we have time to run an entire AB test and um honestly yeah I think that's as good a solution as any uh we do need to stratify that by users so the same user has to be either in the a group or the B group cannot be in both and then we run that for a while we need to get some statistics of the like the magnitude of the effect versus how long we ran it and on how many users we measure online metrics which you know you could go with the same things you could go with engagement metrics as online metrics you could also go with just how long users spend on the platform or the number of ads you can show or something like that number of ads is probably a little bit too abstract so let's let's stick to the same engagement metrics but yeah time on platform is also possible here and then once we deploy it we need to make sure we retrain it every once in a while so for a model like this you know content is uploaded all the time things are happening all the time so maybe every few hours I would retrain it and monitor normalized entropy and as long as that's trending in the right direction or at least staying constant I would be launching newer and newer models every four hours automatically and if not then you know the first time I'd probably let a go the second time i' probably get alerted on the on call speaking of which uh I would probably monitor the inputs and outputs to every stage so every ml model even this one needs to have inputs and outputs monitored outputs are usually my fault as an mle uh inputs are usually the data team's fault but I still I'm not so much caring about assigning blame but I need to know what's happening to my model in production and I will alert the right on calls uh after that so so yeah so uh we can do that and that's basically it and I did not make it in 30 minutes which is okay you actually have about 37 minutes uh or more even like 40 sometimes uh to cover everything in this interview my interviewer was incredibly kind to me and didn't really have a lot of questions uh to direct back in me but I feel like as long as you keep the interview moving and as long as you give your interviewer a perception that you'll get there at least right like so the reason I outlined early what I'm going to say and when is because I don't want my interviewer in this stage being like okay like what is the model here or what is the model here I want to make sure that that is covered later and that their brain is at rest test that it will be covered later also remember that you don't need to hit every single point here you just need to make sure that you give your interviewer enough do watch the ml system design video it'll really help you solidify the ideas I talked about here
Up Next

HNSW Vector Search: Implementation with Faiss in Python
@jamesbriggs
50.3K views•2021-10-05

BitTorrent Protocol Explained: Piece Selection & Peer Choking
@StevenGordonAU
481 views•2013-02-22

HTTP Requests Explained: GET, POST, PUT, DELETE
@codecademy
103.1K views•2021-10-07

Enigma Machine Mechanics: WWII Encryption Explained
@JaredOwen
13.2M views•2021-12-11
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Computer Science
![Foundations for Machine Learning | Linear Algebra, Probability, Calculus, Optimization [Lecture 1]](https://i.ytimg.com/vi_webp/C8hEa2qb46k/maxresdefault.webp)






































