The interviewer asked you to build a series of airplanes. How to design the micro service interface?


This article is the second in a series of back-end microservice architectures. In microservice architecture, there are two common ways of communication between servicesRPCand REST

The article is updated every week. Your “three companies” are my greatest affirmation. WeChat can search the public for the first time to read the official account of “backend Technology School” (usually one to two updates earlier than blogs).

About micro service and micro serviceRPCFor more details, please refer to the article I asked in my last interview: microservices, service governance, RPC, and next generation microservice framework… To help you understand it thoroughly!

What is the main content of this articleRESTStyle design andRESTfulInterface. After reading this article, you will gain the following knowledge points:

  • What is?RESTandRESTful
  • RESTWhat is the interface design specification
  • RESTWhy design stateless
  • Is interface stateless really stateless
  • RPCandRESTApplicable scenarios

Rest and restful

Rest (representational state transfer)Is a software architecture style. Rest proposes a set of architectural constraints and principles that anyRESTThe framework of constraints and principles is calledRESTfulframework.

Microservices need to communicate with each other to complete specific business processing. In a typical client server design model, client and server interact and cooperate through message request response,RESTIt is such a set of design constraints and principle specifications for the interaction interface between microservices.

At first glanceRESTEvery word of “expressional state transition” can be recognized without knowing what it means. No wonder this is the authorRoy Thomas FieldingThe concepts put forward in his doctoral dissertation are all academic terms, but those who are interested can go to see the original paper of the author, and I will post the address:…

Today, lemon helps you understand this concept thoroughly in vernacular. Let’s break down the “expressional state transition” to find out what is “expressiveness” and what is “state transition”.


In fact, “expressiveness” is lack of subject, and subject is “resource”. The complete description is resource expressiveness, that is, resource description. How to describe resources in network communication? Yes, it isUri (Uniform Resource Identifier)

Here are a few synonyms for you first popular science:

URIIs a uniform resource identifier, used to uniquely identify a resource.

URLIs a unified resource locator, which is a specificURI, i.eURLIt can be used to identify a resource, and it also indicates how to locate the resource,URLyesURIA subset of.

URNUnified resource naming is to identify resources by name.URN So is itURIA subset of.
The interviewer asked you to build a series of airplanes. How to design the micro service interface?

stayHTTPIn the agreementURLIdentify resources, that is, the list of web addresses you see in the browser address bar.

The interviewer asked you to build a series of airplanes. How to design the micro service interface?

Resource expressiveness

In order to illustrate the advantages of resource description interface design, let’s make a comparison of interface design methods.

Traditional interface design

Let’s take a look at the traditional network communication mode. hypothesislemonThe object of this character, in the server, is stored in a form ofc++OfclassType storage.

The following procedure shows that the client sends a request and the server creates alemonObject.

  1. Server defined storage structure header filelemon.h
class lemon{
  string name;
  string address;
  uint64 phone;
  1. The client code refers to the server definedlemon.hCross referencing header files increases service coupling!
  2. Client initializes alemonThe instance is sent to the server through the network interface after being serialized.
class lemon lm; = "lemon";
lm.address = "Shenzhen"; = 18666666666;
  1. The server receives the message, deserializes it, and stores the transmitted datalemonobject
Resource expressive interface design

lemonThe internal objects of this service can be represented by a picture or includedlemonName, address, telephone number, etcxmlorjsonFormat data representation.

name : "lemon",
address:  "ShenZhen",
phone  :  18666666666
<?xml version="1.0" encoding="UTF-8" ?>

in other words,lemonThe storage form of this “resource” in the service is invisible to the outside world. External clients can use different resource expression formats to obtain the resources of the server.

(if the server can speak, his heartosIt’s like this: the client doesn’t care how I save this object. As long as you say clearly what you want, just send a request.

The interviewer asked you to build a series of airplanes. How to design the micro service interface?

The most obvious benefit of this is that the coupling between services is reduced. The client does not need to know the specific storage format of the resource in the server before accessing the service resource. It only needs to describe the resource form to modify, create, update and delete the server resource.

state transition

Now that you understand resource description, what is state transition? State transition means that the client drives the resource state of the server to change through a series of request actions. The state of the resource can be transferred between create modify view delete.

The interviewer asked you to build a series of airplanes. How to design the micro service interface?

The macro response of resource state change is business process promotion. For example, you open an account in the banking system, check the balance, and close the account. In this process, you promote your bank account. This “resource” has experienced different state transitions, enabling you to complete different business operations.

Constraints for rest

Protocol selection

RESTIt doesn’t mention what protocol should be used at the bottom. The most commonly used protocol in daily practice is based onHTTPOfRESTfulrealization.

that is becauseHTTPVerbs that come with the agreementGET/POST/PUT/DELETEIt can be used as a method to push the state transitionHTTPThe standard status code is established. There are othersHTTPFeatures that make theHTTPImplementation aboveRESTIt’s much simpler, and if you use other protocols, you need to implement these features yourself.

Request specification

RESTfulIn the architecture, the state transition occurs in the “resource”, soURIIn general, it can only contain nouns representing “resources”, and is recommended to be pluralURIA verb that operates on a resource.

On resourcesCurd "add, delete, modify and search"The action should be in theHTTPOf the request methodGET/POST/PUT/DELETEIt is embodied in.

Rest compliant writing method:

POST    //Create
Get     //Inquiry
PUT     //Modification
DELETE  //Delete

Writing method that does not conform to rest specification:

POST   //Create
POST    //Inquiry
POST   //Modification
POST   //Delete

Status code

The server message response carries the status code to instruct the client to process the next step. accord withRESTfulStandard interface return status codes are universal, and do not need additional conventionsHTTP status code status codeIt represents the result of request processing and reduces the cost of interoperability between microservices.

Status code Meaning of status code
2xx Success, the operation was successfully received and processed
3xx Redirection, further action is required to complete the request
4xx Client error, request contains syntax error or cannot complete request
5xx Server error, the server encountered an error while processing the request

Here are the common onesHTTPStatus code:

  • 200 – Request successful
  • 301 – resources (web pages, etc.) are permanently transferred to other URLs
  • 404 – the requested resource (web page, etc.) does not exist
  • 500 – internal server error


RESTfulThe interface requirement is stateless. Stateless means that any web request must be completely isolated from other requests. When the client initiates a request, the message itself contains all the information required by the server to identify the request context.

No state is not really no state

The “stateless” of the interface is more exactly stateless on the server side. The whole session still needs state maintenance. In order to complete a business process, the client and the server need to interact with each other many timesHTTPThe protocol is a “stateless protocol”, which requires the server to be able to identify several independentHTTPRequest status information to associate them with a business process.

Another example is the withdrawal of funds from the sub banking system

  • In order to log in to the banking system, lemon needs to input the user name and password in the login page first, and then a login request is generated
  • The server receives the login request, executes the login logic and returns the operation result
  • After lemon logs in, he clicks to withdraw 1 million yuan and generates a withdrawal request
  • The server receives the withdrawal request, executes the withdrawal logic and returns the operation result

The interviewer asked you to build a series of airplanes. How to design the micro service interface?

There is a problem here. The server receives login request and withdrawal request at different time points, both of which are userslemonIf we don’t do it on a technical levelHTTPIf the request is associated, the server cannot know that the two requests are actually userslemonPart of the “withdrawal business”.

Technical solutions

There are two technical solutions for the server to identify the “status information” of the request

  1. SessionMethods. The server saves the session state, which is carried by the client every time it requestssession-id

    The server maintains a list of session state information and uses thesession-idUniquely identifies a status message,session-idGenerally included inHTTPResponsiveSet-CookieThe header is returned to the client, and the subsequent client request carries thesession-idInformativecookieHeader, server side parsingcookietake outsession-idTo retrieve the status information corresponding to the message from the maintenance status list, so that the statelessHTTPIt becomes stateful.

The interviewer asked you to build a series of airplanes. How to design the micro service interface?

  1. TokenMethods. The server does not save the session state, and the client carries complete session state information (usually encrypted) to the server every time it requests.

    TokenAlso known as “token” or temporary certificate signature, status information is encrypted totokenThis will decrypt every time the server receives a requesttokenThe status information corresponding to the request can be obtained, and different request messages can be associated with the same business processsessionThis method has a similar effect, but this time the status information is not saved in the server.

The interviewer asked you to build a series of airplanes. How to design the micro service interface?

The first of the above two implementationsSessionThe way is stateful, the secondTokenThe way is stateless.

If you want to make it happenRESTfulThe interface is best implemented according to the second technical solution. Of course, there are other ways to realize stateless. The idea is “the server does not maintain session state”.

Why no state

In order to meet the requirements of high availability and load balancing, multiple micro services are distributed and clustered by load balancing, each service in the cluster is independent and peer-to-peer. If the server is unavailable or down when receiving the client request, stateless requests can be processed and responded by any other available server, which is very important in distributed applications.

The interviewer asked you to build a series of airplanes. How to design the micro service interface?

Imagine that if the server keeps the state, every request in a transaction must be handled by the same server, which will lose the significance and advantage of distribution.

So,RESTfulThe interface requirement is stateless in order to better adapt to distributed business scenarios and play the advantages of microservice cluster.

Rest and RPC

These two concepts often appear in microservice architecture design,RESTIt is a software architecture interface design style,RPCIt is a kind of computer communication protocol. It seems to be two different concepts. If we want to compare them together, I prefer to put them togetherRESTMaterialized into a kind ofHTTPAnd in accordance withRESTThe communication protocol of constraint design can be compared between the two communication protocols.

RPC in retrospect

RPC (Remote Procedure Call)Remote procedure call is a computer communication protocol. Our general program calls are local program calls,RPCIt allows you to call another program’s function just like calling a local function, which involves network communication and interprocess communication, but you don’t need to know the implementation details,RPCThe framework blocks the underlying implementation for you.RPCIt’s a server clientClient/Serv erPattern, the classical implementation is a system of information interaction by sending request and receiving response.

Applicable scenarios

quite a lotRPCThe message transmission provided by the framework is based on binary, such asThriftProtocol buffers。 The advantage of this method is that the message structure is relatively compact, and it can significantly reduce the network overhead for the application scenarios with frequent calls or large traffic and low delay requirements; another constraint is that someRPCThe framework has strong technical coupling, such asDubboCan only be used forjavaTechnology stack. In conclusion,RPC It is more suitable for efficient communication between micro services in the system.

RESTfulThe interface is based onHTTP OfRESTDesign standard, onlywebFramework supportHTTPProtocol and designRESTfulIt is convenient to access and call third-party services,Interface design standards suitable for external exposure of microservice systems.

Write it at the end

This paper is a small aspect of interface selection in the design of microservice architecture. Many people will think that job interview, whether it is a large factory or a small company, is interviewing to build an airplane and screw up the work. I think that even if you can’t get in touch with the work of architecture, you should have a heart of architecture and highly determine cognition. If you only stare at the screw in your hand, what is the difference between it and salted fish?

Old rules. Thank you for your reading. The purpose of this article is to share your understanding of knowledge. I will repeatedly verify technical articles to ensure accuracy to the greatest extent. If there are obvious mistakes in the article, please point out that we can learn together through discussion.

Well, that’s all for today’s technology sharing. This article is the second part of the back-end development microservice design series. This series should continue to be updated. See you next time.

My more wonderful articles:

Very detailed Linux C / C + + learning route summary! Offered by Tencent
Linux “process” problems do not panic, senior programmers teach you 6 moves to deal with!
Interviewer: are you familiar with MySQL affairs? Let me ask you 10 questions
I used big data to analyze the recruitment needs of more than 1000 jobs in first tier cities, and told you how to find a job scientifically
Tencent background development interview written C + + knowledge points reference notes
Can you still play like this? I use vscode to draw class diagram, flow chart, sequence diagram, state diagram, not too cool!
Interviewer: how many redis distributed locks do you know? I can do three!
The most detailed personal blog tutorial building tutorial githubpages + Jekyll simple style blog

It’s not easy to create. Just like it, pay attention to it and support it

You can search the official account of WeChat for “back end technology school” to reply to “information”. Articles are updated every week, see you next time!

Recommended Today

Summary of recent use of gin

Recently, a new project is developed by using gin. Some problems are encountered in the process. To sum up, as a note, I hope it can help you. Cross domain problems Middleware: func Cors() gin.HandlerFunc { return func(c *gin.Context) { //Here you can use * or the domain name you specify c.Header(“Access-Control-Allow-Origin”, “*”) //Allow header […]