{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"],"fields":{"title":{"boost":1000.0},"text":{"boost":1.0},"tags":{"boost":1000000.0}}},"docs":[{"location":"","title":"Umbra Notes","text":""},{"location":"books/api_design_patterns/part1/chapter1/","title":"Introduction to APIs","text":"

API: Application Programming Interface

"},{"location":"books/api_design_patterns/part1/chapter1/#what-are-web-apis","title":"What are web APIs?","text":""},{"location":"books/api_design_patterns/part1/chapter1/#what-are-resource-oriented-apis","title":"What are resource-oriented APIs?","text":""},{"location":"books/api_design_patterns/part1/chapter1/#so-why-arent-all-apis-rpc-orinented","title":"So why aren't all APIs RPC-orinented?","text":"

One of the main reasons is the idea of statefulness.

Consider the following API method names:

  1. ScheduleFlight()
  2. GetFlightDetails()
  3. ShowAllFlights()
  4. CancelReservation()
  5. RescheduleFlight()
  6. UpgradeTrip()

Each one of these RPCs is pretty descriptive, but we have to memorize these methods, each of which is subtly different.

We need to standardise, by providing a standard set of building blocks - method-resource

  1. CreateFlightReservation()
  2. GetFlightReservation()
  3. ListFlightReservation()
  4. DeleteFlightReservation()
  5. UpdateFlightReservation()

Resource-oriented APIs will be much easier for users to learn, understand and remember.

"},{"location":"books/api_design_patterns/part1/chapter1/#what-makes-an-api-good","title":"What makes an API \"good\"?","text":"

What is the purpose of building an API in the first place?

  1. We have some functionality that some users want.
  2. Those users want to use this functionality programmatically
"},{"location":"books/api_design_patterns/part1/chapter1/#operational","title":"Operational","text":""},{"location":"books/api_design_patterns/part1/chapter1/#expressive","title":"Expressive","text":""},{"location":"books/api_design_patterns/part1/chapter1/#simple","title":"Simple","text":""},{"location":"books/api_design_patterns/part1/chapter1/#predictable","title":"Predictable","text":"

APIs that rely on repeated patterns applied to both the API surface definition and the behaviour.

Users very rarely learn an entire API, they learn the parts they need to and make assumptions when they need to make additions. e.g. if a query parameter is called text in one endpoint, it should not be called string or query in another.

APIs that rely on repeated, predictable patterns are easier and faster to learn; and therefore better.

"},{"location":"books/api_design_patterns/part1/chapter1/#summary","title":"Summary","text":""},{"location":"books/api_design_patterns/part1/chapter2/","title":"Introduction to API Design Patterns","text":""},{"location":"books/api_design_patterns/part1/chapter2/#what-are-api-design-patterns","title":"What are API Design Patterns?","text":"

A software design pattern is a particular design that can be applied over and over to lots of similar software problems, with only minor adjustments. It is not a pre-built library but more of a blueprint for solving similarly structured problems.

"},{"location":"books/api_design_patterns/part1/chapter2/#why-are-api-design-patterns-important","title":"Why are API Design Patterns Important?","text":"

Pagination Pattern: The pagination pattern is a way of retrieving a long list of items in smaller, more manageable chunks. The pattern relies on extra fields on both the request and response.

Moving from a non-paginated to paginated response pattern:

Q. What happens if we don't start with the pattern?

  1. All previously written clients are expected all the data in one list - it has no way of getting subsequent pages.
  2. Clients are left to think they have all the data - which can lead to incorrect conclusions.
"},{"location":"books/api_design_patterns/part2/chapter3/","title":"Naming","text":"

In every software system we build, and every API we design or use - there are names that will live far longer than we ever intend them to. It is important to choose great names.

"},{"location":"books/api_design_patterns/part2/chapter3/#why-do-names-matter","title":"Why do names matter?","text":"

When designing and building an API, the names we use will be seen by & interacted with all users of the API.

"},{"location":"books/api_design_patterns/part2/chapter3/#what-makes-a-name-good","title":"What makes a name \"good\"?","text":""},{"location":"books/api_design_patterns/part2/chapter3/#expressive","title":"Expressive","text":"

It is critical that a name clearly convey the thing is it naming.

"},{"location":"books/api_design_patterns/part2/chapter3/#simple","title":"Simple","text":" Name Note UserSpecifiedPreferences Expressive, but not simple enough UserPreferences Both simple & expressive Preferences Too simple"},{"location":"books/api_design_patterns/part2/chapter3/#predictable","title":"Predictable","text":""},{"location":"books/api_design_patterns/part2/chapter3/#language-grammar-syntax","title":"Language, Grammar & Syntax","text":"

Language being inherently flexible and ambiguous can be a good thing and a bad thing.

"},{"location":"books/api_design_patterns/part2/chapter3/#language","title":"Language","text":"

Use American English.

"},{"location":"books/api_design_patterns/part2/chapter3/#grammar","title":"Grammar","text":""},{"location":"books/api_design_patterns/part2/chapter3/#imperative-actions","title":"Imperative Actions","text":"

REST standard verbs should use the imperative mood. They are all commands or orders.

"},{"location":"books/api_design_patterns/part2/chapter3/#prepositions","title":"Prepositions","text":""},{"location":"books/api_design_patterns/part2/chapter3/#pluralisation","title":"Pluralisation","text":""},{"location":"books/api_design_patterns/part2/chapter3/#context","title":"Context","text":"

This means we need to keep the context of our API in mind.

"},{"location":"books/api_design_patterns/part2/chapter3/#data-types-and-units","title":"Data types and units","text":"

A name can become more clear when using a richer data type.

"},{"location":"books/api_design_patterns/part2/chapter4/","title":"Resource Scope and Hierarchy","text":""},{"location":"books/api_design_patterns/part2/chapter4/#what-is-a-resource-layout","title":"What is a resource layout?","text":"

The arrangement of resources in our API, the fields that define those resources, and how those resources relate to one another through those fields.

In other words, resource layout is the entity (resource) relationship model for a particular design of an API.

"},{"location":"books/api_design_patterns/part2/chapter4/#types-of-relationships","title":"Types of Relationships","text":""},{"location":"books/api_design_patterns/part2/chapter4/#reference-relationships","title":"Reference Relationships","text":"

The simplest way or two resources to relate to one another is by a simple reference.

A message resource contains a reference to a specific user who authored the message. "},{"location":"books/api_design_patterns/part2/chapter4/#self-reference-relationships","title":"Self-Reference Relationships","text":"An employee resource points at other employee resources as managers and assistants."},{"location":"books/api_design_patterns/part2/chapter4/#hierarchical-relationships","title":"Hierarchical Relationships","text":" ChatRoom resources act as the owner of Message resources through a hierarchical relationship.

In this case, there is an implied hierarchy of ChatRooms containing or owning Messages.

"},{"location":"books/api_design_patterns/part2/chapter4/#choosing-the-right-relationship","title":"Choosing the Right Relationship","text":""},{"location":"books/api_design_patterns/part2/chapter4/#do-you-need-a-relationship-at-all","title":"Do you need a relationship at all?","text":"

When building an API, after we've chosen the list of things or resources that matter to us, the next step is to decide how these resources relate to one another.

Reference relationships should be purposeful and fundamental to the desired behaviour. Any reference relationship should be something important for the API to accomplish its primary goal.

"},{"location":"books/api_design_patterns/part2/chapter4/#references-or-in-line-data","title":"References or in-line data","text":"

Optimise for the common case - without compromising the feasibility of the advanced case.

"},{"location":"books/api_design_patterns/part2/chapter4/#hierarchy","title":"Hierarchy","text":"

The biggest differences with this type of relationship are the cascading effect of actions and the inheritance of behaviours and properties from parent to child.

"},{"location":"books/api_design_patterns/part2/chapter4/#anti-patterns","title":"Anti-patterns","text":""},{"location":"books/api_design_patterns/part2/chapter4/#resources-for-everything","title":"Resources for Everything","text":"

It can often be tempting to create resources for even the tiniest concept you might want to model.

Rule of thumb: If you don't need to interact with one of your resources independent of a resource it's associated with, then it can probably be a data type.

"},{"location":"books/api_design_patterns/part2/chapter4/#deep-hierarchies","title":"Deep Hierarchies","text":"

Overly deep hierarchies can be confusing and difficult to manage.

Page 63 4.3.3 in-line everything

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/","title":"Chapter 1: Reliable, Scalable and Maintainable Applications","text":"

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

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#thinking-about-data-systems","title":"Thinking about Data Systems","text":"

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).

One possible architecture for data system that combines several components

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#reliability","title":"Reliability","text":"

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.

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#hardware-faults","title":"Hardware Faults","text":"

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).

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#software-faults","title":"Software Faults","text":"

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:

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#human-errors","title":"Human Errors","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#scalability","title":"Scalability","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#describing-load","title":"Describing Load","text":"

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:

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

SELECT tweets.*, users.*\nFROM tweets\nJOIN users ON tweets.sender_id = users.id\nJOIN follows ON follows.followee_id = users.id\nWHERE follows.follower_id = current_user\n
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.

Twitter's data pipeline for delivering tweets to followers, with load parameters

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#describing-performance","title":"Describing Performance","text":"

Once you have described the load on your system, you can investigate what happens when load increases.

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.

Illustrating mean and percentiles: response times for a sample of 100 requests to a service

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.

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.

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."},{"location":"books/designing_data_intensive_applications/part1/chapter1/#approaches-for-coping-with-load","title":"Approaches for Coping with Load","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#maintainability","title":"Maintainability","text":"

Majority of the cost of software is not initial development, but in on going maintenance:

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)

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#operability-making-life-easy-for-operations","title":"Operability: Making Life Easy for Operations","text":"

\"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:

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:

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#simplicity-managing-complexity","title":"Simplicity: Managing Complexity","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter1/#evolvability-making-change-easy","title":"Evolvability: Making Change Easy","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/","title":"Chapter 2: Data Models and Query Languages","text":"

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.
"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#relational-model-vs-document-model","title":"Relational Model Vs Document Model","text":"

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).

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#the-birth-of-nosql","title":"The Birth of NoSQL","text":"

#NoSQL is retroactively interpreted as Not Only SQL.

There are several driving forces behind the adoption of NoSQL databases:

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#the-object-relational-mismatch","title":"The Object-Relational Mismatch","text":"

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.
Representing a LinkedIn profile using a relational schema.

Here is the same data stored as a JSON object:

{\n  \"user_id\": 251,\n  \"first_name\": \"Bill\",\n  \"last_name\": \"Gates\",\n  \"summary\": \"Co-chair of the Bill & Melinda Gates... Active blogger.\",\n  \"region_id\": \"us:91\",\n  \"industry_id\": 131,\n  \"photo_url\": \"/p/7/000/253/05b/308dd6e.jpg\",\n  \"positions\": [\n    {\n      \"job_title\": \"Co-chair\",\n      \"organization\": \"Bill & Melinda Gates Foundation\"\n    },\n    {\n      \"job_title\": \"Co-founder, Chairman\",\n      \"organization\": \"Microsoft\"\n    }\n  ],\n  \"education\": [\n    {\n      \"school_name\": \"Harvard University\",\n      \"start\": 1973,\n      \"end\": 1975\n    },\n    {\n      \"school_name\": \"Lakeside School, Seattle\",\n      \"start\": null,\n      \"end\": null\n    }\n  ],\n  \"contact_info\": {\n    \"blog\": \"http://thegatesnotes.com\",\n    \"twitter\": \"http://twitter.com/BillGates\"\n  }\n}\n

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.

One-to-many relationships forming a tree structure"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#many-to-one-and-many-to-many-relationships","title":"Many-to-One and Many-to-Many Relationships","text":"

In the previous example region_id are given as IDs, not as plain-text strings. This is because:

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.

Extending resumes with many-to-many relationships"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#are-document-databases-repeating-history","title":"Are Document Databases Repeating History","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#the-network-model","title":"The Network Model","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#the-relational-model","title":"The Relational Model","text":"

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:

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#comparison-to-document-databases","title":"Comparison to Document Databases","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#relational-versus-document-databases-today","title":"Relational Versus Document Databases today","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#which-data-model-leads-to-simpler-application-code","title":"Which data model leads to simpler application code?","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#schema-flexibility-in-the-document-model","title":"Schema Flexibility in the Document Model","text":"

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:

if (user && user.name && !user.first_name) {\n // Documents written before Dec 8, 2013 don't have first_name\n    user.first_name = user.name.split(\" \")[0];\n}\n

On the other hand, in a \"statically typed\" database schema-on-write approach.

ALTER TABLE users\nADD COLUMN first_name text;\nUPDATE users\nSET first_name = split_part(name, ' ', 1);\n

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#data-locality-for-queries","title":"Data Locality for Queries","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#convergence-of-document-and-relational-databases","title":"Convergence of document and relational databases","text":"

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#query-languages-for-data","title":"Query Languages for Data","text":"

SQL is a declarative query language.

Imperative example:

function getSharks() {\n    var sharks = [];\n    for(var i = 0; i < animals.length; i++) {\n        if (animals[i].family === \"Sharks\") {\n            sharks.push(animals[i]);\n        }\n    return sharks;\n}\n
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.

SELECT * FROM animals WHERE family = 'Sharks';\n

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.

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#declarative-queries-on-the-web","title":"Declarative Queries on the Web","text":"
<ul>\n    <li class=\"selected\"><p>Sharks</p></li>\n    <li><p>Whales</p></li>\n    <li><p>Fish</p></li>\n</ul>\n
li.selected > p {\n    background-color: blue;\n}\n

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.

const liElements = document.getElementsByTagName(\"li\");\nconst selectedLiElements = liElements.filter(liElement => liElement.className === \"Selected\")\nfor (selectedElement : selectedLiElements) {\n    for (child : selectedElement.childrenNodes()) {\n        if (child.tagName === \"p\") {\n            child.setAttribute(\"style\", \"background-color: blue\")\n        }\n    }\n}\n

"},{"location":"books/designing_data_intensive_applications/part1/chapter2/#mapreduce-querying","title":"MapReduce Querying","text":"

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

SELECT date_trunc('month', observation_timestamp) as observation_month, sum(num_animals) AS total_animals\nFROM observations\nWHERE family = \"Sharks\"\nGROUP BY observation_month;\n

Example in MongoDB using MapReduce

db.observations.mapReduce(\n    function map() {\n        var year = this.observationTimestamp.getYear();\n        var month = this.observationTimestamp.getMonth();\n\n        return [`${year}-${month}`, this.numAnimals];\n    },\n    function reduce(key, values) {\n        return Array.sum(values);\n    },\n    query: {\n        family: \"Sharks\"\n    },\n    out: {\n        \"monthlySharkReport\"\n    }\n);\n

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.

{\n    \"$match\": {\n        \"family\": \"Sharks\"\n    }\n},\n{\n    \"$group\": {\n        \"_id\": {\n            \"year\": {\n                \"$year\": \"$observationTimestamp\"\n            },\n            \"month\": {\n                \"$month\": \"$observationTimestamp\"\n            }\n        },\n        \"totalAnimals\": {\n            \"$sum\": \"$numAnimals\"\n        }\n    }\n}\n

Aggregation pipeline language is similar in expressiveness to a subset of SQL, but it uses JSON syntax rather than SQL's English sentence style.

"},{"location":"books/designing_data_intensive_applications/preface/","title":"Preface","text":"

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.

This is opposed to compute-intensive where the CPU is the bottle neck.

"}]}