r/AskComputerScience • • Sep 23 '15

How do databases work with things like Youtube comments and Facebook likes?

I just started reading about Brewer's Cap Theorem and it made me realized how much I didn't know about databases. There's so much new terms I need to look at like ACID and BASE. My question is about the "setup" of databases here. How do the databases work here? Is the database duplicated across all connected computers or is there a powerful constantly-monitored computer that holds the database and the server/nodes read from/write to that database?

My question for now is when I make a comment in a youtube video, how is it stored? Obviously a host/computer in the youtube network is going to receive it and insert it into a database. However, is this a database that's part of a "local" enormous database that's going to be copied to other regions of the world?

For example if I was in New York and I made a comment to video1, does it go to the eastern USA "local" youtube database that's going to be copied over to the midwest + west database in a few minutes and then to the other "large" database youtube nodes across the world?

I'm trying to understand what it means to be consistent in the Brewer's Cap Theorem. How are nodes making sure they have the most updated version? One large database or each computer have its own database?

Thanks!

46 Upvotes

22 comments sorted by

27

u/BonzoESC Sep 23 '15

Disclosure: I work as an engineer at Basho, makers of the Riak database. All opinions and such below are my own.

Facebook and YouTube use an enormous database that's copied to multiple regions of the world. Individual nodes don't care about the most updated version of the database: they care about the version of a record with the most history, or that they have the record at all.

The CAP theorem basically says that during a Partition, you can sacrifice either Consistency or Availability. For YouTube comments or Facebook likes, it's okay if they're a bit out of sync for a while (lack of consistency), but absolutely not okay if they don't work (lack of availability).

Here's how I believe YouTube comments to work:

  1. Posting a comment to video1 will go from your browser to a local or regional YouTube app server

  2. The app server will store your comment in multiple collections: once for the screen that shows all of your comments, once for the whole set of comments on the video, and possibly for other views of comments too. Denormalization spends disk space and write complexity to reduce disk seeks on read. From now on, let's just talk about the copy of the comment on the video.

  3. The app server will write the comment to the local database cluster, which is almost certainly an AP system: comments taking time to show up is a better scenario than not having comments at all.

  4. The local database cluster will store the comment to several nodes within the cluster, and queue it up for replication to other datacenters.

  5. When the remote cluster receives the comment (may be seconds or minutes, depending on how much commenting is going on compared to peak network bandwidth) it too will store it on several nodes. Depending on how the replication system works, it may queue it for replication to other clusters, or simply trust that your local cluster handled fan-out.

  6. At some point, there may be a "full sync" operation, which uses a Merkle tree to sync up large datasets while minimizing coordination and bandwidth.

Deleting comments is similar: just save a new comment-like entity called a "tombstone" that references the original comment and says it's deleted.

YouTube view counts and Facebook like counts can use a CRDT counter.

Facebook likes work basically the same way: add an entry to the CRDT set of likes for a like-able thing, and merge the set at every datacenter. Un-liking something uses whatever CRDT set's semantics are for removing a set member.

2

u/tontoto Sep 23 '15

Deleting comments is similar: just save a new comment-like entity called a "tombstone" that references the original comment and says it's deleted.

I never actually figured out why this is necessary. Why is it so much more effective to use this than to actually just delete the data?

10

u/tRfalcore Sep 23 '15

pushing destructive updates would lead to more errors-- not actual system crashing errors, but situations which are more easily avoided.

Say you update a post then delete it quickly. Say each one of those commands hits a different server and say the times are off cause all computers report different times. Now say those start to sync actions out to the cluster. This sync is non deterministic in its schedule, speed, time, etc. It's easier to just get an "update comment mark as deleted" and then an "update comment set new text" and have some sort of update history than it is to try to to ensure the hard delete happens and that the edit doesn't actually undelete the comment if it syncs afterward cause you want the delete to be the final result.

3

u/BonzoESC Sep 23 '15

Data that doesn't exist or hasn't been replicated to a particular node is represented by its absence. Deleting data is an operation that has to be replicated (so it can be deleted everywhere) and has to have causality tracking (in case somebody with a stale view updates the data while it still exists), which is what the tombstone does: it's an update that says "this thing was deleted at X place in history."

1

u/proskillz Sep 23 '15

Deleting comments is similar: just save a new comment-like entity called a "tombstone" that references the original comment and says it's deleted.

Is this really how they do it? Not just have a boolean deleted flag on the comment record? At high scale is updating records simply not feasible?

2

u/BonzoESC Sep 23 '15

At one level, yeah. A higher-level part of the system may use a deleted_at timestamp to allow a user to undo a delete, and then only delete it from the backend after 24h or something.

To a database with causality tracking (i.e. to be more predictable than "last write wins," which is fundamentally broken), an update or a delete is going to keep multiple versions of a record (called "siblings") around to help resolve any conflicts (telling versions apart using some kind of "causal context") later on. The data may eventually be garbage collected when the database is compacted/vacuumed/merged, but that's not guaranteed.

With a distributed database, you don't have the same concept of "current time" that a single human brain or even a single computer does: write A to a datacenter in Miami and write B to a datacenter in Tokyo may happen at exactly the same wall-clock time, but a node in Miami will see A followed by B, and a node in Tokyo will see B followed by A.

What's the correct behavior when a user edits and deletes a comment from different browser tabs at the same time from the database's perspective?

What's the correct behavior when one user deletes their comment while another user replies to it at the same time from the database's perspective?

1

u/proskillz Sep 23 '15

Thanks for the detailed explanation, I've only worked on single DB node systems with clustered application servers, so these challenges haven't come up.

1

u/berlinbrown Sep 23 '15

Two questions:

  • Is there a moment in time when the comment won't be available to the rest of the world. And how long does that happen? Let's say I am in America and I post something to reddit or youtube. Are you saying it may not show up in India, for several hours?

  • Also, are 'likes' different than comments. Let's say I am on reddit and like something, should that like count distribute to the entire world, say... hours later?

Also, how does a front end developer build a website like say reddit or youtube? How do I pull data for the number of likes on a page? Is it completely tied to a service? When I look at reddit.com, is all the data from that page pulled from reddit.com for that request? Or are parts of the page coming from, saying...mylikesnode00001.reddit.com?

2

u/mcowger Sep 23 '15

Is there a moment in time when the comment won't be available to the rest of the world.

YES.

Are you saying it may not show up in India, for several hours?

Several hours is unlikely, but several seconds wouldn't be uncommon.

Also, are 'likes' different than comments. Let's say I am on reddit and like something, should that like count distribute to the entire world, say... hours later?

Again, its probably closer to seconds and minutes, but yes.

Also, how does a front end developer build a website like say reddit or youtube? How do I pull data for the number of likes on a page? Is it completely tied to a service?

For sites of this size, its highly optimized and service/database specific. Its probably pulling from whatever the local database cluster is.

1

u/berlinbrown Sep 23 '15

For sites of this size, its highly optimized and service/database specific. Its probably pulling from whatever the local database cluster is.

I mean, old school, we a front-end middleware developer might do:

Putting number of likes on a page: select num_likes from like_database where userid ='123123' ...

I wonder if the dev will build some json rest service:

ajax.pull(likes_service, id=123);

...

But at the same time, in the back-end, what would that look like, in terms of network requests, etc.

2

u/BonzoESC Sep 23 '15

Is there a moment in time when the comment won't be available to the rest of the world. And how long does that happen? Let's say I am in America and I post something to reddit or youtube. Are you saying it may not show up in India, for several hours?

There is definitely a latency between a comment being posted to a datacenter in, say, New York and New Delhi: aside from network latency (i.e. why you play TF2 on a local server instead of one an ocean away), there may be a queue for replication if the available bandwidth isn't enough for the rate updates show up.

That said, I'd expect the delay to be a few seconds, because queues filling up causes problems.

Also, are 'likes' different than comments. Let's say I am on reddit and like something, should that like count distribute to the entire world, say... hours later?

Likes are a bit different from comments: you can post comments all day, while you should only be able to like a Facebook post zero or one times. Think of a comment thread as a List<Comment{User, Body}>, while liking something is a Set<Like{User}>. To provide the Set invariant, the collection of likes can be stored as some flavor ofSet CRDT, depending on how well-liked the post is.

Cut some time out of your day and read this for more about CRDTs, it's worth it: http://hal.upmc.fr/file/index/docid/555588/filename/techreport.pdf

Also, how does a front end developer build a website like say reddit or youtube? How do I pull data for the number of likes on a page? Is it completely tied to a service? When I look at reddit.com, is all the data from that page pulled from reddit.com for that request? Or are parts of the page coming from, saying...mylikesnode00001.reddit.com?

Reddit, YouTube, Twitter, and Facebook didn't all launch with distributed infrastructures; they started small, got successful, and grew to support the traffic.

Here's how a low-traffic website I'd make today would work.

  1. App server receives request proxied through HTTPS terminator/load balancer/front-end web server.

  2. App server makes queries against PostgreSQL to store and load data.

  3. App server sends complete response back to front-end web server.

And here's how a distributed system works:

  1. Front-end app server receives request proxied through HTTPS terminator/load balancer/front-end web server.

  2. App server makes queries against internal services to store and load data.

  3. App server sends complete response back to front-end web server.

The difference is instead of working with a single point of truth, it's communicating with other services that provide encapsulation and abstraction for how they work, like object-oriented programming but over a network. Probably the biggest difference is in planning around failure: if my app can't hit Postgres, it's going to throw up an error screen because there's nothing else it can do without Postgres. On the other hand, if Facebook's "trending hashtags" service is down, there's still lots of Facebook to render, so they just skip that part of the page.

Here's how Twitter moved from a single Rails app ("monorail") to a distributed architecture over the course of several years: https://vimeo.com/55503728

1

u/berlinbrown Sep 23 '15

Cool.

I am at twitter, facebook. I wonder how they decide 'what' data should be fed into the distributed system. Anything that changes? Or, is all data treated equal. For example, there is user data, tweets, likes. What about 'news', blog entries. And then, is there any reason to store/persist in a RDBMS. Should all be distributed.

2

u/BonzoESC Sep 23 '15

I don't have a great answer beyond it being an engineering and business decision.

Different collections of data have different needs: Twitter needs to ingest 6k tweets/second on average, so that's a good candidate for some kind of AP distributed storage system. New user accounts are less-often created, and they have uniqueness requirements about names and email addresses, so having that storage system be CP makes sense.

Once you have the need and capability to pick storage backends at a more granular level than "everything," using that choice to optimize for latency, flexibility, or infrastructure cost becomes possible.

1

u/berlinbrown Sep 23 '15

Should ALL databases be designed this way? Should a company favor a distributed, key-value database like Dynamo as opposed to a heavier RDBMS like Mysql or Oracle?

It seems like we fit everything into a RDBMS.

2

u/mcowger Sep 23 '15

Not all should be. Your bank, for example, shouldn't be....there, the guarantees around things like ACID are more important than performance. A bank would rather be down than get the money wrong.

It seems like we fit everything into a RDBMS.

An asutute point. Especially in the SMB markets, and parts of enterprise, we do shove stuff that doesn't need to be in an RDBMS just because its well known and accessible. Its a tradeoff - is it better to use a perfect database but not be able to find many people to run it, or use an imperfect one but have a larger talent pool?

1

u/berlinbrown Sep 23 '15

But your bank may have some kind of system like a user forum that I suspect is probably all RDBMS.

2

u/mcowger Sep 23 '15

Agreed, and the point I'm trying to make is that different applications have different requirements, so ALL databases shouldn't be designed this way.

2

u/BonzoESC Sep 23 '15

Absolutely not! The vast majority of deployed web applications can fit their data in an RDBMS instance, and discarding the assumptions that, say, Postgres on a single node lets you make costs a lot of engineering time that can usually be better used making customers happy.

1

u/berlinbrown Sep 23 '15

I should have worded it differently. Should applications at least integrating NoSQL into their applications. It looks like a lot of apps, do one or the other.

2

u/BonzoESC Sep 23 '15

Use technologies where it makes sense to: they're tools, not religions.

However, in my experience, the assumptions SQL lets me make are more powerful than the ones non-SQL databases support. Foreign keys, unique indexes, and joins are powerful tools for reasoning about data, and in most cases I never outgrow what fits in a single machine.

I won't say non-SQL databases aren't worth learning, because they absolutely are, even if only to help understand the benefits of SQL.

2

u/omapuppet Sep 23 '15

Is the database duplicated across all connected computers or is there a powerful constantly-monitored computer that holds the database

Both of those models have their uses. Very large distributed systems like YouTube and Facebook are usually set up as many regional clusters of many individual data servers with replication moving data across the system. Within a cluster the data may be sharded such that individual servers handle different parts of the data store. Because of the way data replicates across the system different users may not all see the same view of the data at the same time (that is, C is less important than A and P). This is acceptable because in such a system the lack of consistency isn't normally a significant problem, unless replication latency is really high they probably won't ever notice. Other kinds of systems may use a database system that looks like one gigantic, high-powered database that gives strong guarantees about what users will see when. This is useful for some kinds of business systems where C and A are very important, but P isn't as critical (like users are mostly on the same campus, so regional network problems are low risk).

The actual replication strategy varies depending on what kind of database technology is in use and the requirements of the system with regards to factors like acceptable latency, conflict resolution, etc.

1

u/berlinbrown Sep 23 '15

How does Facebook or Reddit or Youtube decide which components need a distributed database and which parts don't? And how does a front end web developer consume services from different pieces.

I am thinking of reddit. But let's say I want to add 'likes' next to a link. Is that data for the likes pulled from the likes service? And then what about other pieces of the page? Upvotes vs number of readers?