[Front-end development in the microservice/API era] Introduction to BFF--5 practical BFF use cases

foreword

What does the BFF do, simply put, the API server is responsible for the logical part of the business domain, and the BFF is the server that supports the user interface. If web applications could be simply created using domain logic, then there would be no need for BFF. But in the era of microservices/APIs, front-end development increasingly needs to "summarize APIs" and "perform server-side rendering".

So this time, we will introduce five typical use cases of BFF.

  1. API Gateway
  2. Server Side Rendering
  3. Session Management¶
  4. File Upload
  5. WebSocket、Server Sent Events、Long Polling

The use cases of BFF can be roughly divided into two categories, replacing some functions of the client like Server Side Rendering, or acting as an intermediary between the back-end API server and the client and simplifying API implementation.
However, it's an anti-pattern for doing anything with BFFs. BFFs are used for the use cases presented in this article, but it's also important not to make the BFF as thick as possible by changing the implementation of the backend API server-side or client-side. I'll talk more about anti-patterns next time.


API Gateway

API Gateway, as the name implies, is the entrance to the API. As a bridge for the back-end API, aggregate multiple APIs into one, or translate the response results of the API into the format required by the client.

API Gateway mainly has the following functions:

  • API Aggregation that integrates backend APIs
  • API Translation that translates API data for customers
  • API Cache that saves the query results of the API in the cache
  • API Filter that filters information in API responses to reduce data size

In this article, we will explain API Aggregation as a typical function.
When building a client using microservices, one function may be implemented by multiple APIs (multiple microservices). For example, "When displaying the page, obtain the list information of the diary from the diary list API, and obtain multiple comments from the comment list API at the same time". In this case, multiple APIs need to be requested at the same time.

However, there is a limit to the number of simultaneous requests a browser can make. With HTTP/1.1, only a maximum of 6 connections can be established at a time. Even if you want to batch request the API, you will get this limit. Also, checking the session and establishing a TCP connection every time a request is made increases the cost of connecting to the server.
insert image description here
BFF can combine this API into one request. This way you are not limited by the number of browser requests. In addition, network resources can be accessed more efficiently since only one session check and TCP connection is required.
insert image description here


Server Side Rendering

Receiving JSON from the server and building HTML on the client is called "client rendering", while building HTML using common code on the client and server is called server side rendering (SSR).

insert image description here
Today's web applications not only return HTML, but also use JSON as the data format in many cases to construct HTML on the client, but there are still many cases that require the server to render HTML, especially "search engine optimization" and "accelerated initial display" when.

Search Engine Optimization

Search engine crawlers represented by Google have the function of executing JavaScript, and can create indexes after building HTML through Client Side Rendering. However, search engine crawlers are not perfect, and JavaScript execution is not always efficient. Some crawlers do not support the new JavaScript syntax. If it is an infinite scrolling webpage, the content is only refreshed when the page is scrolled. Since the crawler does not scroll the page, it cannot obtain the refreshed content after scrolling.

Accelerated initial display

In addition, in Client Side Rendering, JavaScript needs to be loaded first to build HTML, so it will consume more time. In Server Side Rendering, the HTML exists from the beginning, so the initial display will be faster.

insert image description here
Universal Application

Server Side Rendering generally uses a common mechanism that can run on both Client Side and Server Side to build HTML. If you only consider implementation, you may build View on the client and server at the same time, which can easily lead to repeated development. To avoid this, the same mechanism (JavaScript in the case of web applications) needs to be used for rendering on both the server and client side. This mechanism is called "universal application".

insert image description here
There have been many cases recently where React.js or Vue.js are used for rendering on both the client and server sides. React.js has a "Next.js" framework that enables server-side rendering. In Vue.js, server-side rendering can also be achieved relatively easily using frameworks such as "Nuxt.js".


Session Management¶

Session management is a feature that preserves user information.

The session management session here refers to the user session when there is two-way communication between the client and the server. In order to manage user sessions, the server needs to know who the client is. In many cases, we provide cookies to visiting users and manage "user information" associated with cookies. User information includes user ID, name, avatar, "logged in" and so on.

These user information are frequently accessed and require high-speed access. Therefore, it tends to be stored in a cache such as Redis or memcached. If BFF realizes the function of retrieving information such as "who is the client" from high-speed data storage, the back-end server does not need to maintain the state of the user, and the implementation of the API server becomes simple.

Let's specifically consider an EC (e-commerce) service that uses a shopping cart. In EC service, the following operations are often performed.

  • Show items to buy
  • Add the item you want to buy to the shopping cart
  • Make payment at the cash register

insert image description here
Since the purchase has not been established when the action of step 2 is executed, we store the product data in the shopping cart in the session without sending a request to the backend API to reduce the product inventory. When you do what you did in step 3, the process is complete and a request is made to the backend to destock the item.

insert image description here
In this way, session management is used to maintain a temporary state for the client.

If BFF is not available, client-side storage such as cookies, local storage, and indexed databases can be used. But in this case, it is impossible to manage a large number of states, and you need to pay attention to security issues.

Also, if you let the backend API server manage sessions, you need to store the same state on every other microservice API server, which increases duplicate processing. Using BFF for session management can reduce security risks and make the implementation of the backend API easier.


upload files

File upload refers to the function of uploading media files such as pictures and videos and text files such as TXT and CSV. When uploading a file, it is usually divided into chunks according to the file size and sent bit by bit, so it is difficult to implement with simple request/response processing, and it is relatively difficult to implement as an API. Letting the BFF take care of this layer simplifies the implementation of the API server.

File uploads also tend to be inefficient if built with only the client and API server without BFF. A particularly common practice is to encode the file content on the client side with base64, etc., convert it into text information, and then POST it to the server side in the form of JSON.

When using base64 encoding, it will be converted to text containing padding and line breaks, so the capacity will increase to about 1.4 times. If it is a 5MB file, it will be sent as 7MB, which is very inefficient.

In order to reduce the amount of data transmission, the file can be divided into chunks and sent bit by bit as binary data, or sent as multi-part of FORM instead of text-based JSON and other methods. This is not possible with a simple JSON-based API.

Therefore, the BFF will be the primary recipient of file uploads. Its role is to use form/multi-part instead of JSON to accept files, block large files, receive block data bit by bit, and save the file to the server.

In doing so, you only need to pass the storage path of the file to the backend API, keeping the implementation of the API simple.
insert image description here
Like this, the API proxy between the backend API server and the client is also one of the roles of BFF. File upload is an example, and WebSocket below is a similar case.


WebSocket、Server Sent Events、Long Polling

WebSocket, Server Sent Events, and Long Polling are HTTP extensions for instant communication between clients and servers. In particular, WebSocket is a communication method suitable for applications with strong real-time characteristics such as chatting and synchronous editing, and is widely used in applications such as SNS. Likewise, Server Sent Events and Long Polling are a communication method used when receiving instant notifications and performing processing.

These implementations are very different from API servers that use the JSON format for simple interactions. It is necessary to set up an endpoint (Endpoint) that accepts WebSocket, where data is exchanged in real time and stored in a database table. If BFF is used as this endpoint, the implementation of the backend API server will be simpler.

The diagram below shows the real-time communication between the API server and the client in charge of the BFF

insert image description here
The browser as the client performs "establish a connection with the WebSocket and send a message". The sent message is received by the BFF, and the BFF executes "2. Put the message into the message queue".

The message queue executes "3. Send messages to all BFF instances" (when the number of clients connected to the BFF server at the same time increases, in order to maintain high availability, BFF instances need to be created on multiple servers).

After receiving a message in the queue, send a message to the recipient, "4. Another client received the message". After completing these real-time synchronization processes, BFF performs the process of "5. Registering messages on the backend server".
Similar to the previous File Upload, the backend API is also read here.


How to get started when using BFF

In this article, we introduce 5 typical cases.

  • API Gateway
  • Server Side Rendering
  • Session Management¶
  • File Upload
  • WebSocket、Server Sent Events、Long Polling

Beyond that, there are other use cases such as the "Circuit Breaker" feature and the "API Cache" feature that returns temporary data when the backend API breaks.

However, if all functions are put on the BFF, the load will be concentrated on the BFF, and it may not be able to perform its original duties. BFF is the server of the user interface layer. Due to the architectural pattern when building microservices and rich web applications, it is not recommended to implement too many functions on BFF.

It is recommended to start with typical usages such as API Gateway and Server Side Rendering, and gradually add functions. So in the next article, I will introduce how to start using BFF.

Guess you like

Origin blog.csdn.net/qq_44182284/article/details/124038145