185 points · by weitzj · 6y ago · 152 comments
For example - your internal backend A, calls service B, which then calls some other service C - so it's easy to log that A called B, but the fact that C was called because of what A asked is not, though if propagated (through the tag) then C can report - well I was called by B, but that was on on A to pay.
Then dapper, their distributed tracing was helpful in the few times I had to deal with oncall (actually them asking me to do it). And in general, it felt like you don't have to write any low-level sockets code (which I love)
I'm sure that in 10 years, there will be more concepts like "trace IDs" that we will consider minimally necessary for distributed service architectures, that don't exist today.
FWIW, writing the libs to do the metadata injection/extraction is pretty straightforward and transparent to application developers if they're done right.
this function gets called a couple hundred million times per week, and has never failed as far as I know
I use https://github.com/jrockway/opinionated-server as the foundation of my server-side apps. I thought about monitoring, tracing, and logging once... and then get it for free in every subsequent project. I explode the app into my cluster, and traces are immediately available in Jaeger, I can read/analyze my logs, and it's all a pleasure to debug. I think everyone should just have their own thing like this, because it's definitely a pain to do it more than once, but a joy once you have it working.
(My thing specifically is missing some things I now need, though, like multiple loggers so you can turn on/off rpc tracing at runtime, support for auto-refreshing TLS certs from a volume mount now that everything is mTLS, etc. Will be added when I am less lazy ;)
While I'm here I'll also plug https://github.com/jrockway/json-logs for making the structured logs enjoyable to read. You can query them with jq, it understands all the popular JSON log formats, and I can't live without it. It's the only client-side app I've ever written that passes the "toothbrush test" -- I use it twice a day, everyday. Recommended ;) (Someday I will write docs and an automated release process.)
- How should I pass an argument? Let me count the many ways:
1. Path parameters
2. Query parameters in the URL
3. Query parameters in the body of the request
4. JSON/YAML/etc. in the body of the request
5. Request headers (yes, people use these for API tokens, API versions, and other things sometimes)
- There's also the REST verb that is often super arbitrary. PUT vs POST vs PATCH... so many ways to do the same thing.- HTTP response codes... so many numbers, so little meaning! There are so many ways to interpret a lot of these codes, and people often use 200 where they really "should" use 202... etc. Response codes other than 200 and 500 are effectively never good enough by themselves, so then we come to the next part:
- HTTP responses. Do we put the response in the body using JSON, MessagePack, YAML, or which format do we standardize on? Response headers are used for... some things? Occasionally, responses like HTTP redirects will often just throw HTML into API responses where you're normally using JSON.
- Bonus round: HTTP servers will often support compressing the response, but almost never do they allow compressing the request body, so if you're sending large requests frequently... well, oops.
I don't personally have experience with gRPC, but REST APIs can be a convoluted mess, and even standardizing internally only goes so far.
I like the promise of gRPC, where it handles all of the mundane transport details for me, and as a bonus... it will generate client implementations from a definition file, and stub out the server implementation for me... in whatever languages I want.
Why wouldn't you want that?
gRPC is not a magic bullet for the problems of state management. It'll have all the same issues RPC has had for the last 30 years in that it enforces no discipline where it counts, state management.
The real problem with REST is that state management across a distributed system is hard, real hard. So hard actually that we decide to ignore that it's a problem at all and instead get obsessed with client side interface code, transport protocol, or content types etc, the easy mechanical stuff.
gRPC wont be a magic bullet, just like CORBA wasn't, or XML-RPC, or SOAP. History does like to repeat itself...
It's a complete waste of time and energy for everyone involved. Every one of these questions creates additional mental overhead and an opportunity for incorrect implementation. I would rather deal with meaningful decisions as often as possible, like questions of state management, instead of constantly deciding what color to paint the bike shed based on each person's interpretation of what "the most RESTy" API should look like.
You didn't seem to disagree with me in any way... I see nowhere in your comment where you say that REST APIs are better than gRPC, or why you would pick to make a REST API over gRPC or vice versa. Your rant just has nothing to do with my comment, as far as I can tell?
I never claimed that `gRPC` would solve state management. I never even mentioned state management.
So... cool? gRPC is not a magic bullet, I completely agree. It's a tool, and it seems to have advantages over REST APIs. That's what we're discussing here, since the OP asked why someone would use gRPC.
Your comment seems to imply that it's pointless to improve one problematic situation (RPC) without completely fixing all other problems in existence.
I will commend gRPC for being brave enough to attach "RPC" to its name in 2020. Can't say the same for that quisling GraphQL, which is neither what I would call a query language nor has anything to do with graphs. A- for marketing effort, I suppose.
> it enforces no discipline where it counts, state management
A tale as old as time. If your redux app is a bloated confusing mess, then try scaling down your department from 100 devs to the 10 that it actually needs. Most devs are bad at organization. Most devs are just bad in general. Ever see a bad developer grapple with TypeScript? I wager most codebases fall apart from disarray long before they reap any of the presumed benefits of most "best" practices. You can't fix social problems with technology. And code hygiene and state hygiene are fundamentally social issues. People think tools like Prettier can come around and clean their house for them. Like some Roomba for code. Even the best Roomba will smear dog shit all over the place.
service ThingService {
rpc CreateThing(CreateThingRequest) returns (Thing);
rpc DeleteThing(DeleteThingRequest) returns (ThingDeleted); // No arguing about if this is within the HTTP spec and supported as it just works :)
rpc UpdateThing(...) returns (Thing);
rpc ListThings(...) returns (stream Thing);
}
[1] - https://google.aip.dev/121One of my biggest gripes with REST APIs is having identifiers in url path instead of in query params or the request body
HTTP verbs. REST is a protocol-neutral architectural style (of which HTTP is an implementation), it doesn't have verbs.
> that is often super arbitrary. PUT vs POST vs PATCH...
They aren't arbitrary, they have well-defined semantic differences. It's true that “REST” APIs built over HTTP often play fast and loose with HTTP semantics, but that's not a feature of REST so much as people understanding neither REST not HTTP.
> HTTP response codes... so many numbers, so little meaning!
HTTP Status Codes have very well defined meanings.
> Response codes other than 200 and 500 are effectively never good enough by themselves, so then we come to the next part
201, 202, 204, 3xx, 4xx, and 5xx are usually fine alone, though sometimes it's nice to augment 4xx/5xx with additional info.
200, on the other hand, usually needs more info unless it's being used in a case where 201/204 would be more specific.
These have clearly defined caching and indempotency differences. They are not the same. I don't believe gRPC handles this or it looks like its experimental.
Clearly defined...? Maybe?
I don't know of any popular HTTP proxies that rely on these definitions to automatically decide how to cache things, because people in the real world follow the definitions very loosely. GET is the only one that I've seen relied on, and it's still just a good bet, not a guarantee. Usually, you have to define which routes are cacheable and carefully configure the cache settings... in my experience, at least.
Maybe it's just my bad luck to have encountered all the ways these verbs aren't used consistently over the years. They're a hint towards what will happen... at best. In my experience, anything goes, no matter what the verb says.
I truly hope you've had a better experience, and that it's just me.
> I don't believe gRPC handles this or it looks like its experimental.
Which seems fine. We can't rely on HTTP verbs for state management because of how inconsistent implementations are, so I don't expect gRPC to do that either, but at least gRPC won't make you choose a random verb.
What doesn't have great support for Content-Encoding headers?
See this stackoverflow question for one brief discussion: https://stackoverflow.com/q/20507007
I've looked around for this feature and rarely found it to be supported... but it's also rarely discussed.
If you want to avoid bikeshedding for REST APIs, adopt a standard like JSON API [1].
Adopt a specification standard like OpenAPI [2] and JSON Schema [3]. There is tooling to give you the client/server stubs like gRPC.
Implement using HTTP/2 with fallback to HTTP and you get compression and multiple channels per connection.
gRPC is a repeat of CORBA is a repeat of ONC-RPC is a repeat of... there's common reasons why RPC as a concept is brittle and tightly couples implementations of clients and servers.
[1] https://jsonapi.org/ [2] https://swagger.io/specification/ [3] https://json-schema.org/
This is like saying all programs should be written in C, because otherwise programmers forget about how memory allocation works and the cost involved.
Any good REST client implementation abstracts away the remoteness too, apart from occasionally returning a network error the caller. I’m definitely not sitting there twiddling bits to call a REST API.
> It requires both server and client to agree on the definition.
This is true of literally every API. If the client and the server disagree on a REST API call, nothing good is going to happen. Period.
gRPC is designed to allow evolution of APIs where clients and servers have different versions of the IDL. It’s no more brittle than a JSON API, and arguably it’s actually less brittle because of how the approach it takes.
> It requires a different naming service from the standard internet naming service (DNS) which is brittle across network boundaries.
That is unequivocally false.
It doesn’t use a special naming service to connect servers and clients, unless you specifically choose to override the default behavior, which you could also do with JSON API if you wanted to make it really brittle as well.
Instead just use DNS, which is the default for both.
It absolutely doesn’t require a special naming service, as you claim.
gRPC is built on the HTTP/2 standard. Based on the rest of your comment, you clearly also didn’t know this.
> gRPC is a repeat of CORBA is a repeat of ONC-RPC is a repeat of... there's common reasons why RPC as a concept is brittle and tightly couples implementations of clients and servers.
Your information so far can be trivially disproven, so... apologies if I’m not going to take advice from you on this subject right now.
I’m glad JSON API works for you.
EDIT: I see you repeated a lot of this misinformation in yet another comment. I get it —- the very idea of RPC is offensive to you. But you should at least research the technology you’re ranting about. Your information about gRPC is entirely, factually wrong.
Although investment in tooling had been significant in the beginning it has truly paid off its dividends now as we can develop in Golang (micro services, CLI), Javascript (SPA) and Python (end to end testing framework), and have a single definition for all our API endpoints and messages in the form of Protobufs. These protobufs automatically generate all client and server code and give us out-of-the-box backward and forward compatibility, increased performance due to binary format over the wire and more..
Our Architect which put together most of this infrastructure has written an entire series of blog posts about how we use gRPC in practice, detailing our decisions and tooling: https://stackpulse.com/blog/tech-blog/grpc-in-practice-intro...
https://stackpulse.com/blog/tech-blog/grpc-in-practice-direc...
https://stackpulse.com/blog/tech-blog/grpc-web-using-grpc-in...
"About 2 months ago I started working at StackPulse. When I joined there was not a single line of code written yet. We’ve had to decide on many different things. One of those things was choosing a “protocol” for communication both between our micro services and externally".
- You want to have inter-service RPC.
- You want not only unary calls, but also bidirectional streaming.
- You want a well-defined schema for your RPC data and methods.
- You want a cross-language solution that guarantees interoperability (no more JSON parsing differences! [1])
[1] - http://seriot.ch/parsing_json.phpThere are plenty of commercial, proprietary ASN.1 tooling solutions out there. Presumably it's why ASN.1 has persisted as long as it has in industry. Even Fabrice Bellard sells a commercial solution: https://bellard.org/ffasn1/ When you have access to good tooling ASN.1 is arguably superior to the open source alternatives as there aren't as many broken corner cases that can cause interoperability problems.
We only have ourselves to blame. If I ever have time I want to write an ASN.1 spec parser using LPeg that can generate LPeg-based DER parsers. I already have a fairly comprehensive LPeg-based DER parser for PKIX messages, but generating that from an ASN.1 spec is a significant step up in conceptual complexity. While I've written more than my fair share of parsers before, I've never written a proper parser generator, so it's a steeper hill to climb for me even though I already have more ASN.1 experience than most.
How do I code gen clients/servers for Java, Python, Golang, C++, Node, PHP, etc. How can I instrument distributed tracing for requests? How do I talk to these services from my web frontend (grpc web equivalent)? How do I talk to these from my embedded system (proto lite equivalent)?
This is especially rich when you're comparing protobuf to ASN.1 - which is probably mostly known for having dozens of competing, obscurely-named encoding formats to choose from. And for them being so complex to implement that it regularly causes bugs and security issues in software...
and there are people who complain it's too simple, i.e no comments
Much better developer experience and performance writing HTTP services and code to call them.
Cons are * not being able to use Postman / firebug, nothing on the wire is human-readable * load balancer support is sketchy because of the use of HTTP trailers and full path HTTP/2. That's why AWS ALB supporting it is news. * The auth story isn't very clear. Do you use the out of band setup or add tokens in every single RPC?
I think it's actually quite well documented. [1]
You can have out-of-band authentication data per-connection ('per-channel') and per-RPC ('per-call'). SSL certificates can be used per-connection, while token-based authentication (eg. bearer tokens, or anything else that can fit in metadata) can be either.
Sure enough openapi can do all of this I guess but grpc definitions in Protobuf or Google artman are just way quicker to understand and work with. (At least for me)
But from my experience you use the code generator and trust the deserializer and serializer since they are unit tested. So you can just unit test your methods and don’t have to look at the actual binary blob payload.
You trust that gRPC is battle tested and you can just test your code.
You would probably wrap the generated methods/objects/structs in your own domain model and unit test the mapping between them. Using the objects from gRPC throughout your code directly does work but sometimes is not what you want to work with.
So I rather would introduce another boundary to the transport. But that is personal preference (in case I want to get rid of gRPC and don’t want to touch my business logic)
There is some tooling out there for development (https://github.com/fullstorydev/grpcurl and https://github.com/fullstorydev/grpcui are pretty nice) but it's still much less mature than the massive amount of mature tooling available for HTTP-based services. And that is both an artifact of gRPCs relative youth compared to REST and also for some more fundamental reasons (binary wire format, mutual TLS based authentication, etc).
All that said, I've been working with gRPC over the past 6 months or so and overall the development experience is much nicer on net I think.
For in-browser use with gRPCweb, if you use test-proto-on-XHR, things continue to work as with REST/JSON.
For inter-server debugging, you usually defer to opentracing or similar, and capture request data there.
So the spec already includes versioning?
You can rename fields (but keep the tag number and therefore wire format compatibility), add fields (which will be ignored by the other side), remove fields (as all are explicitly optional so every consumer explicitly checks for their presence anyway), ignore unset fields (as the wire encoding is to a certain-degree self-describing), etc.
1. It's standardized all the implementation for each language is roughly similar and has the same feature sets (middlewares, stubs, retry, hedging, timeouts, deadlines, etc).
2. High performance framework/webserver in "every" language. No more "should I use flask or the built in http server or gunicorn or waitress or..."
3. Tooling can be built around schemas as code. There's a great talk that I highly recommend about some of the magic you can do [0].
4. Protos are great for serialization and not just over a network! Need to store configs or data in a range of formats (json, prototxt, binary, yaml)?
5. Streaming. It's truely amazing and can dramatically reduce latency if you need to do a lot of collection-of-things or as-soon-as-x processing.
6. Lower resource usage. Encoding/decoding protos is faster then encoding and decoding json. At high throughput that begins to matter.
7. Linting & standards can be defined and enforced programatically [1]
8. Pressures people to document things. You comment your .c or .java code, why not comment your .proto?
[0] - https://youtu.be/j6ow-UemzBc?t=435
[1] - https://google.aip.dev/
RPC is more lightweight for persistent connections to stateful services. RPC makes broadcast easier than HTTP. Individual RPC requests have (much) less overhead than HTTP requests, which is very helpful when tight coupling is acceptable.
Trying to run, say, MMO gaming servers over HTTP is an exercise in always paying double for everything you want to do. (Also, trying to run a FPS gaming server over TCP instead of UDP is equally not the right choice!)
Seriously binary RPC has been around for ages.
Might have been handy to beat benchmarks back in the day when people liked to whip them out for comparison, but IIS is under 10% according to Netcraft now. Time to fold up the tent and go home.
I suppose .Net Core is sticking with Http.sys to avoid implementing their own web server, but is tying yourself to the Windows shipping cycle worth it ?
[1]: https://docs.microsoft.com/en-us/aspnet/core/grpc/?view=aspn...
Really? There are lots of problems with doing HTTP in the kernel, but “fast moving” is a new one. HTTP was stuck in permafrost from 1995 to 2015. If it weren’t for Google, neither of HTTP 2 or 3 would have ever happened.
Does anyone have experience (good, bad, otherwise) using the gRPC JSON transcoding option for real-world stuff? I'm debating using it (still need REST clients sometimes) but I'm not sure how hacky it is.
They say not to rely on the output being stable, so I would recommend guaranteeing a stable translation yourself for a REST client. You can achieve this by translating from the JSON to your proto or grpc service structure yourself.
Also you should look at Google Artman on github/googleapis as sometimes it felt that defining the REST mappings in Protobuf were lacking some features. Using google artman you kind of mix/match Protobuf with yaml definitions of your service.
We never had to use it, though. It just depends on where you want to put your authentication information. As of today I would probably change my mind and make it explicitly in payload, I.e. Protobuf message and not fiddle with headers any more.
What's the main use-case for gRPC?
I had the impression RPC was seen as a mistake.
Sure, gRPC also uses a binary protocol, but that doesn't seem like a USP of gRPC. Why didn't they went fron non-RPC binary?
Serious question! It sounds a bit counterinuitive to me at the first glance.
1. Performance
2. It's hard to make changes that are backwards incompatible via protobuf (reduces significant source of bugs)
3. Great, standardized observability for every service. Small services don't really need too many custom metrics, since we log a LOT of metrics at the RPC layer
4. Standardization at the RPC layer lets us build useful generic infrastructure - like a load testing framework (where users only need to specify the RPC service, method, and parameters like concurrency, RPS).
Compared to plain JSON/REST RPC, it has all the advantages of protobuf over JSON (ie. strong typing, client/server code generation, API evolution, etc), but also provides some niceties at the transport layer: bidirectional streaming, high quality TCP connection multiplexing, ...
Not really. You'd use it for inter service communication but can't really use it in the browser (see grpc-web)
Why wouldn't it be enough to use REST with a protobuf media type?
1) REST verb/code mapping is too arbitrary for my taste, I prefer explicit verbs in RPC method names and error codes explicitly designed for RPC [2] and ones that will not be accidentally thrown by your HTTP proxy thereby confusing your client
2) REST stream multiplexing over a minimum amount of TCP connections is difficult to do, I trust the gRPC authors to have done their homework better than the average HTTP library. In addition, you can multiplex multiple gRPC bidirectional streams over a single TCP connection, which is something you can't do over plain HTTP without resorting to websockets.
[1] - https://cloud.google.com/endpoints/docs/grpc/transcoding
[2] - https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
For hypermedia/hypertext Fielding made a solid argument for preferring REST over RPC (mostly because of caching). I still recommend reading his very approachable thesis - these days not so much for the web/REST architecture, but for the other ones, which include modern SPAs (they're not great as hypermedia apps, but fine as networked applications):
https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
Apart from caching (and cache invalidation) it's accepted that making the network invisible is a bad idea - it will lead to issues. So remote procedure calls aren't inherently bad, but blurring the distinction too much between local procedure calls and remote ones aren't a great idea. From hung nfs mounts to unpredictable application performance, it is unpleasant.
This Netflix talk on their not-graphql framework gives a very nice summary of when and how you might prefer RPC to REST:
And more to the point, the vast majority of "REST APIs" I've experienced in the wild are just RPC-style APIs that use JSON.
It’s a pretty decent implementation of the pattern though. Efficient binary protocol (unlike SOAP), built in security and none one of the complexity of object request brokers. Although you might actually want that and you’ll likely end up with something complex like Istio.
Aren't REST and webhooks just RPC protocols too?
REST is not, but the thing that isn't REST that lots of people call REST is basically just RPC-over-HTTP-with-JSON.
I thought the difference is, that RPC hides behind a function that looks like it would behave like it was local, but in fact does a remote call and REST explicitly states that things happen remote.
A Remote Procedure is just that, a procedure. Procedures don't have many constraints. They can implicitly change the state of resources on the server. They can do whatever you want.
REST APIs are supposed to be designed around state transfer. You transfer the state of a resource from server to client with a GET. You transfer the state back to the server with a POST/PUT. The operations are supposed to be 'stateless' in that the result is not supposed to depend on the pre-existing state of the resource on the server.
To give a silly example, let's say I have a Counter service. In RPC I could expose a incrementByOne procedure. And then clients could just call:
incrementByOne(id=1)
In REST I would have a Counter resource. The RESTful way to increment the counter would be: GET /api/counter/1
-> OK {'id': 1, 'value': 12}
PUT /api/counter/1 {'id': 1, 'value': 13}
-> OK
It's more cumbersome, but notice that unlike the RPC call, the result of the PUT request doesn't depend on the current state in the server. The counter will always end up at 13. The PUT request is idempotent, I can repeat it n times and end up with the same result. Obviously that's not true with the RPC call. Notice also that the client must implement its own logic for incrementing.You could design a RESTful RPC, where the only methods are like:
getCounter(id) -> Counter
createCounter(Counter) -> id
putCounter(Counter)
The opposite, RPC over REST, doesn't really work. I guess you could try representing procedures as resources but it would be incredibly awkward. That's why I say REST is more constrained.With well designed REST you should end up with very decoupled logic between server and client since all they can do is transfer state, they each have they wholly separate logic to deal with the state.
With RPC you can end up with some real spaghetti, where the logic of client and server are intertwined. But not everything can be modeled cleanly as resources, sometimes you really do just want to execute some logic on the server.
Any remote interface tends to “hide behind” a local function, that's just how structured programming (of which most more advanced paradigms are refinements) works. And Remote Procedure Call is fairly express that things happen remotely.
SOAP is in my experience really hard to use and get right, compared to protobufs that bring well understandable set of primitives and intuitive support in many languages. gRPC is a solid carrier for protobufs. Yes, gRPC has many cons (e.g. with undefined/nil values, etc.), but overall it has worked great for our usecases.
The downsides were:
You can’t rely on ACM for certificate renewal
The LAyer 4 NLB is “too dumb” to balance the traffic. You have a long running http/2 connection and maybe all go to reverse proxy instance A whilst the reverse proxy B replica is idle.
It’s worse than it sounds. For us it worked. And maybe with The TLS support of NLBs and the feature that the NLB can set the ALPN header to h2, you actually might be able to use ACM with NLB for gRPC.
But now with an ALB you get all of these features and can even load balance per request method (since it is layer 7)
So for example you offer a unified Api and one method of this Api has a disproportional amount of traffic, you can do something about this already at the ALB
When does AWS roll out quic support in ALBs?
It will probably be a while. We've been evaluating Quic and the ecosystem just isn't quite ready. We opted to release UDP support instead, so apps that want Quic can do it, but we can avoid adding much extra plumbing in front of the simple HTTP apps.
Given how much AWS is investing in Rust, they'll probably ship first class support for Quic when Hyper does (same as us!): https://github.com/hyperium/hyper/issues/2078
Also the blog posts on grpc.io are interesting, but I find them harder to discover whilst reading the documentation. But here they are: https://grpc.io/blog/
Grasping the concept of a context/deadlines is quite helpful:
https://grpc.io/blog/deadlines/
You could also find related information in the Google SRE Handbook (Service Level Objectives): https://landing.google.com/sre/sre-book/chapters/service-lev...
If you are familiar with Go, the article about "Context" might also be helpful: https://blog.golang.org/context
But in any case, gRPC is language agnostic and has nothing to do with Go.
To get an idea how to create an api-repository with protobuf defintions to be shared by multiple services/clients, one can look at: https://github.com/googleapis/googleapis
Disclaimer: I work at Google, although I would have recommended these resources anyway.