Initial commit
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 47 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 90 KiB |
@@ -0,0 +1,224 @@
|
||||
# Chapter 1: Reliable, Scalable and Maintainable Applications
|
||||
|
||||
Many applications today are *data-intensive*, as opposed to *compute-intensive*. Raw CPU power is rarely a limiting factor for these applications.
|
||||
|
||||
A data-intensive application is built from the following building blocks
|
||||
|
||||
- Store data so that they, or another application can find it again later (*databases*)
|
||||
- Remember the result of an expensive operation, to sped up reads (*caches*)
|
||||
- Allow users to search data by keyword or filter it in various ways (*search indexes*)
|
||||
- Send a message to another process, to be handled asynchronously (*stream processing*)
|
||||
- Periodically crunch a large amount of accumulated data (*batch processing*)
|
||||
|
||||
## Thinking about Data Systems
|
||||
|
||||
Database and a message queue are quite similar. They both store data for some time - though they have very different access patterns which means different performance characteristics and thus very different implementations.
|
||||
|
||||
Boundaries between these implementations are becoming slightly blurred. There are data-stores that are also used as message queues (*Redis*) and there are messages queues with database-like durability guarantees (*Apache Kafka*).
|
||||
|
||||
<figure>
|
||||
<img src="/books/designing_data_intensive_applications/media/ddia_0101.gif">
|
||||
<figcaption>One possible architecture for data system that combines several components</figcaption>
|
||||
</figure>
|
||||
|
||||
When you combine several tools in order to provide a service, the service's interface or application programming interface (API) usually hides those implementation details from clients.
|
||||
|
||||
- *Reliability*: The system should continue to work *correctly* (performing the correct function at the desired level of performance) even in the face of *adversity* (hardware or software faults, even human error).
|
||||
- *Scalability*: As the system *grows* (in data volume, traffic volume or complexity), there should be reasonable ways of dealing with that growth.
|
||||
- *Maintainability*: Over time, many different people will work on the system (engineering and operations, both maintaining current behaviour and adapting the system to new use cases), and they should all be able to work in it *productively*.
|
||||
|
||||
## Reliability
|
||||
|
||||
- The application performs the function that the user expected.
|
||||
- It can tolerate the user making mistakes or using the software in unexpected ways.
|
||||
- Its performance is good enough for the required use case, under the expected load and data volume.
|
||||
- The system prevents any unauthorized access and abuse.
|
||||
|
||||
Things that ca go wrong are called *faults*. Systems that anticipate faults and can cope with them are called *fault-tolerant* or *resilient*. Fault tolerance does not mean making a system tolerant of all faults, but only tolerating *certain types* of faults.
|
||||
|
||||
**NOTE**: A fault is not the same as a failure.
|
||||
|
||||
- A fault is defined as one component of the system deviating from its spec.
|
||||
- A failure is when the system as a whole stops providing the required service to the user,
|
||||
|
||||
It is impossible to to reduce the probability of a fault to zero; therefore it is best to design fault-tolerance mechanisms that prevent faults from causing failures.
|
||||
|
||||
### Hardware Faults
|
||||
|
||||
Hard disks are reported as having a mean time to failing (MTTF) of about 10 to 50 years. So on a storage cluster with 10,000 disks, we should expect on average one disk to die per day.
|
||||
|
||||
A good combatant for this is **redundancy**. Disks may be set up in RAID configurations, servers can have dual power supplies etc. When a component dies, the redundant component can take it's place whilst the broken one is being replaced. This approach cannot complete prevent hardware problems from causing failures, but it is well understood and can often keep a machine running uninterrupted for years.
|
||||
|
||||
However, as data volumes and applications' computing demands have increased, more applications have begun using larger number of machines, which proportionally increase the rate of hardware faults. Moreover, in some cloud platforms such as AWS it is fairly common for virtual machine instances to become unavailable without warning as the platforms are designed to prioritise flexibility and elasticity over single-machine reliability.
|
||||
|
||||
Hence there is a move toward systems that can tolerate the loss of entire machines, by using software fault-tolerance techniques in preference or in addition to hardware redundancy. Such systems also have operations advantages: a single-server system requires planned downtime, whereas a system that can tolerate machine failure can be patched one node at a time with no downtime of the entire system (*rolling upgrade*).
|
||||
|
||||
### Software Faults
|
||||
|
||||
Hardware faults are normally random and independent form each other. This is not the case for software faults. Software fault can lie dormant for a long time until they are triggered by am unusual set of circumstances. Though there is no quick solution, there are lots of small ones:
|
||||
|
||||
- Testing
|
||||
- Process isolation
|
||||
- Allowing crash & restart
|
||||
- Measuring and monitoring
|
||||
|
||||
### Human Errors
|
||||
|
||||
Humans design and build software systems, and the operators are also human. Humans are unreliable.
|
||||
|
||||
10%-25% of outages are caused by hardware faults, the rest are human related faults.
|
||||
|
||||
- Design systems in a way that minimises opportunities for error.
|
||||
- e.g. well designed abstractions, APIs and admin interfaces that make it easy to do "the right thing"
|
||||
- Decouple the places where people make the most mistakes from places where they can cause failures
|
||||
- Provide fully featured non-production *sandbox* environments.
|
||||
- Test thoroughly at all levels, from unit tests to whole-system integration tests & manual tests.
|
||||
- Allow quick and easy recovery from human errors to minimise the impact in the case of failure.
|
||||
- Make it fast to roll back configuration changes
|
||||
- Roll out new code gradually
|
||||
- Provide tools to recompute data
|
||||
- Set up detailed and clear monitoring, such as performance metrics and error rates.
|
||||
|
||||
## Scalability
|
||||
|
||||
Even if a system is working reliably today, that doesn't mean it will necessarily work reliably in the future.
|
||||
|
||||
*Scalability* is the term we used to describe a system's ability to cope with increased load.
|
||||
|
||||
### Describing Load
|
||||
|
||||
Load can be described with a few numbers which we call *load parameters*. These parameters depend on the architecture of the system. It might be:
|
||||
|
||||
- Requests per second
|
||||
- Ratio of reads to writes
|
||||
- Number of simultaneous active users
|
||||
- Hit rate on cache
|
||||
|
||||
Consider **Twitter** as an example, they have two main operations, *post tweet* and *home timeline*. There are two ways of implementing these.
|
||||
|
||||
**Approach 1**: Posting a tweet simply inserts the new tweet into a global collection of tweets. When user requests their home timeline, look up all the people they follow, find all the tweets for each of those users and merge them (sorting on time). In a **relational database**
|
||||
```sql
|
||||
SELECT tweets.*, users.*
|
||||
FROM tweets
|
||||
JOIN users ON tweets.sender_id = users.id
|
||||
JOIN follows ON follows.followee_id = users.id
|
||||
WHERE follows.follower_id = current_user
|
||||
```
|
||||
**Approach 2**: Maintain a cache for each user's home timeline - like a mailbox of tweets for each user. When user *posts a tweet*, look up all the people who follow that user, and insert the new tweet into each of their home timeline caches. The request to read the home timeline is the cheap, because its result has been computed ahead of time.
|
||||
|
||||
<figure>
|
||||
<img src="/books/designing_data_intensive_applications/media/ddia_0103.gif">
|
||||
<figcaption>Twitter's data pipeline for delivering tweets to followers, with load parameters</figcaption>
|
||||
</figure>
|
||||
|
||||
The first version of Twitter used approach 1, but the systems struggled to keep up with the load of home timeline queries, so the company switched to approach 2. The average rate of published tweets is almost two orders of magnitude lower than the rate of home timeline reads, so in this case its preferable to do more work at write time and less at read time.
|
||||
|
||||
However the downside of approach 2 is posting a tweet now requires a lot of extra work. On average a tweet is delivered to about 75 followers, so 4.6K tweets/second became 345k writes/second to home timeline caches. However now consider some accounts have 30 million followers.
|
||||
|
||||
Twitter uses a hybrid of both solutions. For users with smaller follow counts approach 2 is used, however for celebrity accounts approach 1 is used and these two timelines are merged together.
|
||||
|
||||
### Describing Performance
|
||||
|
||||
Once you have described the load on your system, you can investigate what happens when load increases.
|
||||
|
||||
- When you increase a load parameter and keep the system resources unchanged, how is the performance of your system affected?
|
||||
- When you increase a load parameter, how much do you need to increase the resources if you want to keep performance unchanged?
|
||||
|
||||
> **LATENCY AND RESPONSE TIME**
|
||||
>
|
||||
> *Latency* and *response time* are often used synonymously, but they are not the same.
|
||||
> **Response time**: Is what the client sees: the sum of service time, network delays and queuing delays.
|
||||
> **Latency**: Is the duration that a request is waiting to be handled - during which it is *latent*, awaiting service.
|
||||
|
||||
<figure>
|
||||
<img src="/books/designing_data_intensive_applications/media/ddia_0104.gif">
|
||||
<figcaption>Illustrating mean and percentiles: response times for a sample of 100 requests to a service</figcaption>
|
||||
</figure>
|
||||
|
||||
Most requests are reasonably fast, but there are occasional *outliers* that take much longer. Perhaps these requests are intrinsically more expensive - however even the same request will see variations due to all matter of reasons.
|
||||
|
||||
*Average* response time of a service is common however it is not a very good metric if you want to know your "typical" response time - it doesn't tell you how many users actually experienced that delay.
|
||||
|
||||
*Percentiles* are a better metric.
|
||||
|
||||
- Take all response times, sort them and the *median* is the half way point.
|
||||
- This makes the median a good metric if you want to know how long users typically have to wait: half of users are served in less than the median, the other half longer. The median is also known as the *50th percentile* and abbreviated as *p50*.
|
||||
- Note this refers to a single request. If a user creates multiple requests, the probability that one of them is over the p50 is much greater than 50%.
|
||||
- In order to figure out how bad your outliers are you can look at higher percentiles: the *95th*, *99th* and *99.9th* (abbreviated to *p95*, *p99* and *p999*).
|
||||
- e.g. if p95 is 1.5 seconds, that means 95 out of 100 requests are served quicker than 1.5 seconds, and 5 are served slower.
|
||||
- High percentiles of response times (also known as *tail latencies*), are important because they directly affect users' experience of the service.
|
||||
|
||||
Amazon descries response time requirements for internal services in terms of p999 even though it only affects 1 in 1000 requests. This is because customers with the slowest requests are often those who have the most data in their accounts (valuable customers).
|
||||
|
||||
Queuing delays often account for a large part of the response time at high percentiles. It only takes a small number of sow requests to hold up the processing of subsequent requests - known as *head-of-line blocking*. Due to this it is important to measure response times on client side.
|
||||
|
||||
<figure>
|
||||
<img src="/books/designing_data_intensive_applications/media/ddia_0105.gif">
|
||||
<figcaption>When several back end calls are needed to serve a request, it takes just a single slow back end request to slow down the entire end-user request.</figcaption>
|
||||
</figure>
|
||||
|
||||
#### Approaches for Coping with Load
|
||||
|
||||
**Vertical Scaling**: Moving to a more powerful machine.
|
||||
|
||||
**Horizontal Scaling**: Distributing the load across multiple smaller machines.
|
||||
|
||||
Some systems are *elastic*, meaning that they can automatically add computing resources when they detect a load increase. Elastic systems are useful if load is unpredictable, but manual/periodic scaled systems are simpler and have fewer operational surprises.
|
||||
|
||||
While distributing stateless services across multiple machines is fairly straightforward, taking stateful data systems from a single node to a distributed set up can introduce additional complexity. Common wisdom (until recently) was to keep your database on a single node and vertically scale until cost dictated horizontal scaling.
|
||||
|
||||
## Maintainability
|
||||
|
||||
Majority of the cost of software is not initial development, but in on going maintenance:
|
||||
|
||||
- Fixing bugs
|
||||
- Keeping systems operational
|
||||
- Investigating failures
|
||||
- Adapting to new platforms
|
||||
- Modifying it for new use cases
|
||||
- Repaying technical debt
|
||||
|
||||
**Operability**: Make it easy for operations teams to keep the system running smoothly.
|
||||
|
||||
**Simplicity**: Make it easy for new engineers to understand the system, by removing as much complexity as possible from the system.
|
||||
|
||||
**Evolvability**: Make it easy for engineers to make changes to the system in the future, adapting it for unanticipated use cases are requirements change. (Also known as *extensibility*, *modifiability* or *plasticity*)
|
||||
|
||||
### Operability: Making Life Easy for Operations
|
||||
|
||||
> "Good operations can work around the limitations of bad software, but good software cannot run reliably with bad operations"
|
||||
|
||||
Operation teams are responsible for the following:
|
||||
|
||||
- Monitoring the health of the system and quickly restoring services.
|
||||
- Tracking down the cause of the problems.
|
||||
- Keeping software and platforms up to date, including security patches.
|
||||
- Keeping tabs on how different systems affect each other.
|
||||
- Anticipating future problems and applying fixes before they occur.
|
||||
- Establishing good practices are tools for deployment and configuration management.
|
||||
- Performing complex maintenance tasks such as moving an application from one platform to another.
|
||||
- Maintaining the security of the system.
|
||||
- Defining processes that make operations predictable and help keep the production environment stable.
|
||||
- Preserving the organisations knowledge about the system, even as individuals come and go.
|
||||
|
||||
Good operability means making routine tasks easy - allowing the operations team to focus their efforts on high-value activities. Data systems can do various things to make routine tasks easy:
|
||||
|
||||
- Providing visibility into the runtime behaviour and internals of the system.
|
||||
- Providing good support for automation and integration with standard tools.
|
||||
- Avoiding dependency on individual machines.
|
||||
- Providing good documentation and easy to understand operational model.
|
||||
- Providing good default behaviour.
|
||||
- Self-healing where appropriate.
|
||||
- Exhibiting predictable behaviour, minimising surprises.
|
||||
|
||||
### Simplicity: Managing Complexity
|
||||
|
||||
In complex software, there is a greater risk of introducing bugs when making a change: when the system is harder for developers to understand and reason about, hidden assumptions, unintended consequences, and unexpected interactions are more easily overlooked.
|
||||
|
||||
Complexity can be *accidental*. This is defined if it is not inherent in the problem the software is trying to solve, but only arises from implementation. One of the best tools for removing accidental complexity is *abstraction*.
|
||||
|
||||
### Evolvability: Making Change Easy
|
||||
|
||||
The ease with which you can modify a data system, and adapt it to changing requirements, is closely linked to its simplicity and its abstractions: simple and easy-to-understand systems are usually easier to modify than complex ones.
|
||||
|
||||
*Evolvability* can be thought of the agility on a data system level.
|
||||
@@ -0,0 +1,347 @@
|
||||
# Chapter 2: Data Models and Query Languages
|
||||
|
||||
Data models are perhaps the most important part of developing software. They define on how we *think about the problem* we are solving.
|
||||
|
||||
Most applications are built by layering one data model on top of another. For each layer the key question is: how is it *represented* in terms of the next-lower layer? For example:
|
||||
|
||||
1. Application developer looks at the real world and model in terms of objects/data structures and APIs that manipulate those data structures.
|
||||
2. Storing is done in JSON, a relational database or a graph model.
|
||||
3. Database engineers then map these structures in terms of bytes in memory on a disk or on a network. This representation needs to allow querying, updating, deletion etc.
|
||||
4. Then the physical layer of actual electrical signals.
|
||||
|
||||
## Relational Model Vs Document Model
|
||||
|
||||
In a relational model, data is organised into *relations* (called *tables* in SQL), where each relation is an unordered collection of *tuples* (*rows* in SQL).
|
||||
|
||||
### The Birth of NoSQL
|
||||
|
||||
\#NoSQL is retroactively interpreted as *Not Only SQL*.
|
||||
|
||||
There are several driving forces behind the adoption of NoSQL databases:
|
||||
|
||||
- A need for greater scalability than relational databases can easily achieve, include very large datasets or very high write throughput.
|
||||
- A widespread preference for free and open source software over commercial database products.
|
||||
- Specialised query operations that are not well supported by the relational model.
|
||||
- Frustration with the restrictiveness of relational schemas, and a desire for a more dynamic and expressive data model.
|
||||
|
||||
### The Object-Relational Mismatch
|
||||
|
||||
Most application development today is done in OOP, meaning if data is stored in relational tables, an awkward transition layer is required between the object in application code and the database model of tables, rows and columns. The disconnect between the models is sometimes called an *impedance mismatch*.
|
||||
|
||||
Object-relational mapping (ORM) frameworks reduce the amount of boiler plate required for this translation layer, but they cannot completely hide it.
|
||||
|
||||
For example, storing a resume on a relational schema can be tricky. The profile as a while can be identified by a unique identifier `user_id`. Fields like `first_name` and `last_name` appear exactly once per user so they can be modeled as columns in the table. However most people have had `n` jobs, this is a one-to-many relationship.
|
||||
|
||||
1. In traditional SQL, jobs would be put in a separate table, with foreign keys in the user table.
|
||||
2. There are some DBs that have added standard support for multi-valued data to be stored in a single row
|
||||
3. Encode this information in a string field as JSON.
|
||||
|
||||
<figure>
|
||||
<img src="/books/designing_data_intensive_applications/media/ddia_0201.jpeg">
|
||||
<figcaption>Representing a LinkedIn profile using a relational schema.</figcaption>
|
||||
</figure>
|
||||
|
||||
Here is the same data stored as a JSON object:
|
||||
|
||||
```json
|
||||
{
|
||||
"user_id": 251,
|
||||
"first_name": "Bill",
|
||||
"last_name": "Gates",
|
||||
"summary": "Co-chair of the Bill & Melinda Gates... Active blogger.",
|
||||
"region_id": "us:91",
|
||||
"industry_id": 131,
|
||||
"photo_url": "/p/7/000/253/05b/308dd6e.jpg",
|
||||
"positions": [
|
||||
{
|
||||
"job_title": "Co-chair",
|
||||
"organization": "Bill & Melinda Gates Foundation"
|
||||
},
|
||||
{
|
||||
"job_title": "Co-founder, Chairman",
|
||||
"organization": "Microsoft"
|
||||
}
|
||||
],
|
||||
"education": [
|
||||
{
|
||||
"school_name": "Harvard University",
|
||||
"start": 1973,
|
||||
"end": 1975
|
||||
},
|
||||
{
|
||||
"school_name": "Lakeside School, Seattle",
|
||||
"start": null,
|
||||
"end": null
|
||||
}
|
||||
],
|
||||
"contact_info": {
|
||||
"blog": "http://thegatesnotes.com",
|
||||
"twitter": "http://twitter.com/BillGates"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The JSON model reduces the impedance mismatch between the application code and the storage layer. The lack of schema is often cited as an advantage.
|
||||
|
||||
The JSON representation has better *locality* than the multi-table schema, if you want to fetch a profile in the relational example, you need to perform multiple queries or a join between 2 or more tables. In the JSON format all relevent data is in one place.
|
||||
|
||||
The one-to-many relationships from the user profile to the user's positions, education, contact information etc imply a tree like structure, the JSON representation makes this tree structure explicit.
|
||||
|
||||
<figure>
|
||||
<img src="/books/designing_data_intensive_applications/media/ddia_0202.gif">
|
||||
<figcaption>One-to-many relationships forming a tree structure</figcaption>
|
||||
</figure>
|
||||
|
||||
### Many-to-One and Many-to-Many Relationships
|
||||
|
||||
In the previous example `region_id` are given as IDs, not as plain-text strings. This is because:
|
||||
|
||||
- Consistent style
|
||||
- Avoids ambiguity (if there are several similarly named cities)
|
||||
- Ease of updating - name is only stored in one place
|
||||
- Localisation support
|
||||
|
||||
Whenever you store an ID or a text string is a question of duplication. When you use an ID, the information that is meaningful to humans is stored in only one place and everything that refers to it uses an ID.
|
||||
|
||||
The advantages of using an ID is that because it has no meaning to humans, it never needs to change: the ID can remain the same, even if the information it identifies changes.
|
||||
|
||||
Anything that is meaningful to humans may need to change sometime in the future - and if that information is duplicated, all the redundant copies need to be updated.
|
||||
|
||||
Removing such duplication is the key idea behind *normalisation* in databases.
|
||||
|
||||
Even if the initial version of an application fits well in a join-free document model, data has a tendency of becoming more interconnected as features are added to applications. See below how adding two extra features turns one-to-many to many-to-many.
|
||||
|
||||
<figure>
|
||||
<img src="/books/designing_data_intensive_applications/media/ddia_0204.gif">
|
||||
<figcaption>Extending resumes with many-to-many relationships</figcaption>
|
||||
</figure>
|
||||
|
||||
### Are Document Databases Repeating History
|
||||
|
||||
While many-to-many relationships and joins are routinely used in relational databases, document databases and NoSQL reopened the debate on how best to represent such relationships in a database.
|
||||
|
||||
This debate is much older than NoSQL - going back to the 1970s.
|
||||
|
||||
#### The Network Model
|
||||
|
||||
In the tree structure of the hierarchical model, every record has exactly one parent; in the network model, a record could have multiple parents.
|
||||
|
||||
For example, there could be one record for the `"Greater Seatlle Area"` region and every user who lived in that region could be linked to it. This allowed one-to-many and many-to-many relationships to be modeled.
|
||||
|
||||
The links between records in the network model were not foreign keys, but more like pointers in a programming language. The only way of accessing a record was to follow a path from a root record along these chains of links. This was called an *access path*.
|
||||
|
||||
In the simplest case, an access path could be like the traversal of a linked list: start at the head of the list and look one record at a time until you find the one you want. But in a world of many-to-many relationships, several different paths can lead to the same record, and a programmer working with the network model had to keep track of these different access paths in their head.
|
||||
|
||||
A **query** was performed by moving a cursor through the database by iterating over lists of records and following access paths. If a record has multiple parents (i.e. multiple incoming pointers from other records), the application code had to keep track of all the various relationships.
|
||||
|
||||
#### The Relational Model
|
||||
|
||||
What the relational model did, by contrast, was to lay out all the data in the open: a relation (table) is simply a collection of tuples (rows), and that it. There are no labyrinthine nested structures, no complicated access paths to follow if you want to query data you can:
|
||||
|
||||
- Read any or all of the rows in a table, selecting those that match your conditions.
|
||||
- Read a particular row by designating some columns as a key and matching on those
|
||||
- Insert a new row into any table without worrying about foreign key relationships to and from other tables.
|
||||
|
||||
The *query optimiser* automatically decides which parts of the query to execute in which order, and which indexes to use.
|
||||
|
||||
Those choices are effectively the equivalent of the "access path", but the big difference is it is made by the query optimiser, not the application developer.
|
||||
|
||||
#### Comparison to Document Databases
|
||||
|
||||
Document databases reverted back to the hierarchical model in one aspect: storing nested records (one-to-many) relationships within their parent record rather than a separate table.
|
||||
|
||||
However, when it come to representing many-to-one and many-to-many relationships, relational and document databases both refer using foreign keys.
|
||||
|
||||
#### Relational Versus Document Databases today
|
||||
|
||||
The main arguments in favour of the document data model are schema flexibility, better performance due to locality, and that for some applications it is closer to the data structures used by the application.
|
||||
|
||||
The relational model counters by providing better support for joins, and many-to-one and many-to-many relationships.
|
||||
|
||||
#### Which data model leads to simpler application code?
|
||||
|
||||
If data in your application has a document-like structure (i.e. a tree of one-to-many relationships where typically the entire tree is loaded at once), then the document model makes sense.
|
||||
|
||||
The relational technique of *shredding* - splitting a document-like structure into multiple tables - can lead to cumbersome schemas and complex code.
|
||||
|
||||
If a document model is deeply nested it can cause problems as nested items cannot be queried directly. For example "the second item in the list of employers for user 251" is inefficient.
|
||||
|
||||
However if you applicaiton does use many-to-many relationships, the document model is less appealing. It's possible to reduce the need for joins by denormalising but then the application code needs to do additional work to keep the denormalised data consistent. Joins can be emulated in application code by making multiple requests to the database. But that moves complexity to the application code and multiple calls is usually slower than the optimised JOIN request.
|
||||
|
||||
#### Schema Flexibility in the Document Model
|
||||
|
||||
No schema means that arbitrary keys can values can be added to a document, and when reading, clients have no guarantees as to what fields the documents may contain.
|
||||
|
||||
Document databases are sometimes called *schemaless*, but that's misleading, as the code that read the data usually assumes some kind of structure. A more accurate term is *schema-on-read*. In contrast *schema-on-write* is enforced by the database on writes.
|
||||
|
||||
For example, say you have currently storing user's full name in one field, however now you want to store them separately. In a document database:
|
||||
|
||||
```js
|
||||
if (user && user.name && !user.first_name) {
|
||||
// Documents written before Dec 8, 2013 don't have first_name
|
||||
user.first_name = user.name.split(" ")[0];
|
||||
}
|
||||
```
|
||||
|
||||
On the other hand, in a "statically typed" database *schema-on-write* approach.
|
||||
|
||||
```sql
|
||||
ALTER TABLE users
|
||||
ADD COLUMN first_name text;
|
||||
UPDATE users
|
||||
SET first_name = split_part(name, ' ', 1);
|
||||
```
|
||||
|
||||
Altering the table is relatively quick however setting every row in the table is time consuming.
|
||||
|
||||
The schema-on-read approach is advantageous if the items in the collection don't all have the same structure.
|
||||
|
||||
#### Data Locality for Queries
|
||||
|
||||
A document is usually stored as a single continuous string, encoded as JSON or binary (MongoDB's BSON). If your application often needs access to the entire document (e.g. rendering to a web page), there is a performance advantage to this *storage locality*. If data is split across multiple tables, multiple index lookups are required to retrieve it all.
|
||||
|
||||
The database typically needs to load the entire document, even if you access only a small portion of it. On updates to a document, the entire document usually needs to be rewritten - only modifications that don't change encoded size can be performed in place (rare).
|
||||
|
||||
For this reason its recommended to keep documents small and avoid frequent updates.
|
||||
|
||||
Some relational databases can offer this locality. Oracle's feature: *multi-table index cluster tables* which declares rows should be inter-leaved in the parent table. There is also the *column-family* concept in Cassandra.
|
||||
|
||||
#### Convergence of document and relational databases
|
||||
|
||||
Relational databases have supported XML since their inception - however many now support JSON.
|
||||
|
||||
Document databases now supports relational like joins in its query language and some MongoDB drivers automatically resolve database references.
|
||||
|
||||
It seems that relational and document databases are becoming more similar over time, and that is a good thing: the data models complement each other. If a database is able to handle document-like data and also perform relational queries on it, applications can use the combination of features that best fits their needs.
|
||||
|
||||
### Query Languages for Data
|
||||
|
||||
**SQL** is a *declarative* query language.
|
||||
|
||||
*Imperative* example:
|
||||
```js
|
||||
function getSharks() {
|
||||
var sharks = [];
|
||||
for(var i = 0; i < animals.length; i++) {
|
||||
if (animals[i].family === "Sharks") {
|
||||
sharks.push(animals[i]);
|
||||
}
|
||||
return sharks;
|
||||
}
|
||||
```
|
||||
In relational algebra, you would instead write:
|
||||
$$
|
||||
sharks = \sigma_{family =''Sharks''} (animals)
|
||||
$$
|
||||
|
||||
Where $\sigma$ is the selection operator, returning only those animals that match the condition $family = ''Sharks''$. SQL follows this closely.
|
||||
|
||||
```SQL
|
||||
SELECT * FROM animals WHERE family = 'Sharks';
|
||||
```
|
||||
|
||||
An imperative language tells the computer to perform certain operations in a certain order.
|
||||
|
||||
In a declarative query language, you just specify the pattern of the data you want. e.g. what conditions should be met, how the data should be transformed - but not *how* to achieve that goal. The declarative query language hides the implementation details of the database engine. This allows the database engine to be optimised and improved without the need to change the query language itself.
|
||||
|
||||
Declarative languages are very easy to parallelise - they specify the pattern of results not the algorithm to be used.
|
||||
|
||||
#### Declarative Queries on the Web
|
||||
|
||||
```html
|
||||
<ul>
|
||||
<li class="selected"><p>Sharks</p></li>
|
||||
<li><p>Whales</p></li>
|
||||
<li><p>Fish</p></li>
|
||||
</ul>
|
||||
```
|
||||
|
||||
```css
|
||||
li.selected > p {
|
||||
background-color: blue;
|
||||
}
|
||||
```
|
||||
|
||||
Here the CSS selector `li.selected > p` declares the pattern of elements to colour blue: all `<p>` elements whise direct parent is a `<li>` element which a class of `selected`.
|
||||
|
||||
Doing this with an imperative approach is a nightmare.
|
||||
```js
|
||||
const liElements = document.getElementsByTagName("li");
|
||||
const selectedLiElements = liElements.filter(liElement => liElement.className === "Selected")
|
||||
for (selectedElement : selectedLiElements) {
|
||||
for (child : selectedElement.childrenNodes()) {
|
||||
if (child.tagName === "p") {
|
||||
child.setAttribute("style", "background-color: blue")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- If the *selected* class is removed because the user clicks onto a different page, the colour won't be removed - even if the code is re-run, so the item will remain highlighted until refresh. With CSS the browser automatically detects when the rule no longer applies.
|
||||
- If you want to take advantage of a new API, such as `document.getElementsByClassName()`, the code will have to be entirely re-written. On the other hand browsers can improve the performance of CSS without breaking compatibility.
|
||||
|
||||
#### MapReduce Querying
|
||||
|
||||
*MapReduce* is a programming model for processing large amount of data in bulk across many machines. This is supported by MongoDB as a mechanism for performing read-only queries across many documents.
|
||||
|
||||
MapReduce is neither declarative nor imperative but somewhere in between.
|
||||
|
||||
Example in PostgreSQL
|
||||
```SQL
|
||||
SELECT date_trunc('month', observation_timestamp) as observation_month, sum(num_animals) AS total_animals
|
||||
FROM observations
|
||||
WHERE family = "Sharks"
|
||||
GROUP BY observation_month;
|
||||
```
|
||||
|
||||
Example in MongoDB using MapReduce
|
||||
```
|
||||
db.observations.mapReduce(
|
||||
function map() {
|
||||
var year = this.observationTimestamp.getYear();
|
||||
var month = this.observationTimestamp.getMonth();
|
||||
|
||||
return [`${year}-${month}`, this.numAnimals];
|
||||
},
|
||||
function reduce(key, values) {
|
||||
return Array.sum(values);
|
||||
},
|
||||
query: {
|
||||
family: "Sharks"
|
||||
},
|
||||
out: {
|
||||
"monthlySharkReport"
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
The `map` function would be called once for each document (e.g. returning `["2026-01", 3], ["2026-01", 4]`. Subsequently the `reduce` function would be called `["2026-01", [3,4]]` returning 7.
|
||||
|
||||
Map and Reduce functions must be pure with no side effects (no additional db calls). This allows them to be run anywhere, in any order and re-run on failure.
|
||||
|
||||
MapReduce was replaced by the *aggregation pipeline*.
|
||||
|
||||
```json
|
||||
{
|
||||
"$match": {
|
||||
"family": "Sharks"
|
||||
}
|
||||
},
|
||||
{
|
||||
"$group": {
|
||||
"_id": {
|
||||
"year": {
|
||||
"$year": "$observationTimestamp"
|
||||
},
|
||||
"month": {
|
||||
"$month": "$observationTimestamp"
|
||||
}
|
||||
},
|
||||
"totalAnimals": {
|
||||
"$sum": "$numAnimals"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Aggregation pipeline language is similar in expressiveness to a subset of SQL, but it uses JSON syntax rather than SQL's English sentence style.
|
||||
@@ -0,0 +1,18 @@
|
||||
# Preface
|
||||
|
||||
There many been many developments in distributed systems, databases and the applications build on top of them, there are various driving forces:
|
||||
|
||||
1. Handling huge volumes of data.
|
||||
2. Businesses need to be agile, test hypotheses cheaply and respond quickly to markets.
|
||||
3. Free & open source software has become very successful and is preferred now to commercial or in-house solutions
|
||||
4. CPU clock speeds are barely increasing. But multi-core processors are standard and networks are getting faster. Parallelism is only going to increase.
|
||||
5. Even small teams can now build systems that are distributed across machines and regions - thanks to **IaaS** (think *AWS*)
|
||||
6. Many services are expected to be highly available. Extended downtime is unacceptable.
|
||||
|
||||
An application is *data-intensive* if data is it's primary challenge.
|
||||
|
||||
- The quantity of data.
|
||||
- The complexity of data.
|
||||
- The speed at which data changes.
|
||||
|
||||
This is opposed to *compute-intensive* where the CPU is the bottle neck.
|
||||
@@ -0,0 +1,3 @@
|
||||
# Structure and Interpretation of Computer Programs
|
||||
|
||||
We are about to study the idea of a *computational process*. Computational processes are abstract beings that inhabit computers. As they evolve, processes manipulate other abstract things called data. The evolution of a process is directed by a pattern of rules called a *program*. People create programs to direct processes. In effect, we conjure the spirits of the computer with our spells.
|
||||
1
docs/index.md
Normal file
@@ -0,0 +1 @@
|
||||
# Umbra Notes
|
||||