156 points · by denysonique · 4y ago · 182 comments
I think it’s interesting; I experimented with a higher-magic version of this a couple of years ago. (It had continuations to support returning callbacks, could preserve object identity, and could lift inline anonymous functions to the server with some amount of intelligence.) My goal was to make the RPCs as close as possible to local async functions, which was really fun when it was working.
My experience was that for the simplest use cases, the ergonomics were unbeatable. Just drop a `@remote` tag into your TodoMVC frontend, and there’s your TodoMVC backend. But as soon as I had to look under the hood (for something as simple as caching behavior), the “just a function” interface was a distraction and I found myself wishing for a more conventional RPC interface.
(I think that might be why you tend to see this sort of magic more in the context of a full framework (such as Meteor), where all the typical use cases can be answered robustly. If you’re building your thing out of modules, cleverer abstractions usually mean more work overall to integrate everything and boring is better.)
But it has a section titled "Network Transparency" that talks about when transparency of fails. And he calls out three things that make network calls fundamentally different:
1. Availability. It's possible that your network "function" will be impossible to call for some amount of time.
2. Latency. The round-trip latency of RPC calls is extremely high, which affects API design in major ways. Typically, you wind up wanting to perform multiple queries or multiple operations per round-trip.
3. Reliability. Network calls may fail in many more ways than local calls.
And these are all issues that have defeated many "transparent" RPC systems in the past. Once your application spreads across multiple machines that interact, then you need to accept you're building a distributed system. And "REST versus RPC" is relatively unimportant compared to the other issues you'll face.
Joel Spolsky was not the originator of these ideas; their most famous form comes from about 1994, as written by L Peter Deutsch:
https://en.wikipedia.org/wiki/Fallacies_of_distributed_compu...
Even if you stay fully client-side, you have bits of code that are running in different parts of the browser and you have to marshal data back and forth between them. Many web API functions are really RPC calls into a different browser process.
JS has has primitives like channels, promises or async/await to deal with those.
At least there might be some ways how you could use those as as building blocks for an RPC system which lets you handle the three problems better.
With PWAs web apps can and do work offline or work limited network. There's a whole series of problems this is useful for.
The problem it solves is unnecessary protocol noise and the trade-off is tight coupling between frontend and backend code. I think it's obvious that the trade-off makes sense for small projects and MVPs: most changes require touching both ends and typically the team isn't differentiated between backend and frontend anyway.
But even with large projects that have to cater to many clients, a tightly-coupled RPC system can solve problems like overfetching and underfetching as a straightforward method for implementing the BFF pattern[1].
[1] https://medium.com/mobilepeople/backend-for-frontend-pattern...
Telefunc is about replacing generic endpoints (RESTful/GraphQL APIs) with tailored endpoints (RPC).
That's why the trade-off is simpler architecture (generic endpoints are often an unnecessary abstraction) VS decoupling (tailored endpoints require the frontend and backend to be deployed in-sync).
In the long term I foresee RPC to be also used for very large teams. I've ideas around this, stay tuned. I can even see companies like Netflix ditching GraphQL for RPC, although this won't happen any time soon.
In the meantime, RPC is a natural fit for small/medium sized teams that want to ship today instead of spending weeks setting up GraphQL.
Latency is actually mostly solvable with something like cap’n’proto that pipelines the promises so that you can have a normal looking composable functions without the latency cost.
Joel Spolsky advice is usually fine but it’s important to understand his commentary tends to be about what ideas are in vogue / dominant at the time of the post and tend to have a more limited perspective (vs listening to researchers in the field actively investigating the problems and investing in ways to find solutions).
For example, we have an explicit class that manages RPC calls so that at the call site it looks like a regular function. But since it’s I/O it returns an async so it makes it clear that it’s I/O (which you have to do with non NodeJS JavaScript). Additionally, it returns a promise of a Result object type just like any other failable call which you have to handle properly. Works pretty well (although in retrospect I’m now wishing we had used structured clone instead of JSON to send messages around).
Async vs Sync is not enough. Network partitions have multiple failure modes depending on a range of factors, but one of the most pernicious is the “undetectable cloud break”, an invisible break between two routers. Having a well defined “api” that is the clear “we are communicating over the network here” makes it much easier to reason about and handle these issues.
There is an enormous difference between “this I/O call failed” and “this I/O call took 10 minutes to fail”.
Are HTTP and its cousin REST examples of RPC frameworks? I don’t think so, and I may have misunderstood your point. But if you do consider them to be RPC, can you explain your reasoning?
Despite drawbacks here and there, I do have appreciation for RPC, e.g. JSON-RPC is widely used in the distributed/decentralized tech space I work in. It’s fairly well-specified and well-suited for a variety of use cases:
Telefunc doesn't try to completely abstract away the network: as you say, it's not possible to abstract away network latency and network failure. Telefunc is about creating network endpoints as easily as creating functions.
Exactly.
> the “just a function” interface was a distraction and I found myself wishing for a more conventional RPC interface.
For real-time use cases, I agree. I believe functions are the wrong abstraction here for real-time. I do plan to support real-time but using a "it's just variables" abstraction instead, see https://github.com/brillout/telefunc/issues/36.
> cleverer abstractions usually mean more work overall to integrate everything and boring is better.
Yes, Telefunc's downside is that it requires a transformer. The Vite and Webpack one are reliable and used in production (using `es-module-lexer` under the hood). The hope here is that, as Telefunc's popularity grows, more and more stacks are reliably supported. Also, there is a prototype using Telefunc without a transformer at all, which works but needs polishing.
> I experimented with a higher-magic version of this a couple of years ago.
Neat, curious, is it on GitHub?
That sounds familiar! We were doing all of that for Opalang arount 2009-2010 if I recall my calendar correctly. Were you there?
Are you me? I made this as a fun project a while ago, and left it there gathering dust, but earlier this year it found new life in an AI application and it's delivering promising results.
The wisdom I was given by an old hand is that the computer industry goes through a cycle of focus: disk, network, CPU - at any given time the currently 'hot' technology is targeting one of these hot spots.
I am not sure I have lived long enough to see this play out for myself but it seemed that there was some truth to it when I first heard it.
What I just really dislike is all the fanfare and marketing blah. It seems that we can't have a proper conversation about such things. Performance and bottlenecks are always the same. Something is your current bottleneck. You focus on getting rid of that bottleneck and you discover the next bottleneck. There is always one. People will always take advantage of the bottleneck removed and hit the next one. Can't we just openly talk about the fact that we've removed one and the new bottleneck is of a different 'type' (like you say, disk, network, CPU). Do we always have to pretend like something truly new has been found? Can't we acknowledge what we're really doing there?
Different thing, same vein: The recent posts on here about finite automata (aka state machines). These are the bread and butter of computer science. You learn about those in every computer science 101. And in 101.2 you learn about pushdown automata because finite automata can't do everything you might need (i.e. they can't count). Yet the discussion here and the linked articles and frameworks linked to sound like they're completely novel.
History can't repeat because underlying technology always moves forward and that change is so important that it invalidates almost anything to be clasified as total repete.
Which would you say we're in now?
I wish every CS curriculum had a mandatory course on the history of CS.
Covering how many times the same ideas have been "new" and then discarded as not useful, only to be rediscovered. It could help reduce the amount of churn in the industry, so we can move forward instead of forgetting and relearning the same things over and over.
For example it's not possible to call JS function, it'll work and they it'll fail to return a result for some reason. Worst thing that could happen is stack overflow but it won't let you call this function.
I think that RPC is fine as long as it's clearly separated and those who read and write code do not mask it behind ordinary innocent looking calls. It's OK to call personApi.getFullName(person.fistName, person.lastName). It's not OK to call person.getFullName().
Like which problems?
Transparency? Nope; the caller still needs to set up where the remote function resides, which of the multiple remote functions with that name must be executed, etc.
Latency? It actually makes it harder - you now need separate plumbing so that calls which take more than $X minutes must be considered failure.
Reliability? Not this one either - the error returned by a function will still have to be handled separately from an error returned by the network.
They just provide syntactic sugar papering over them and, what's worse, exactly make you believe that the problems have been solved.
We fought so hard to get rid of crazy RPC protocols (COM+, CORBA) and abominations like SOAP and people keep trying to bring them back.
Yes networking is hard. Do everything you can to make it easier to debug. Text protocols, easy to use tools, etc
They have no idea how thankful they should be HTML friendly ("REST") APIs.
Don't wake the RPC eldritch horrors. Let them dream their undead dreams in the stygian depths.
For those that dare re-kindle the old ways of RPC, only despair, anguish and insanity await. The mindless boilerplate, the infinite depths of parser recursion, the envelopes within envelopes, the madness inducing mysteries of undeclared encoding, the deadly omission of byte order markers, the incomprehensibly complex, yet vague error messages... and the network. The network is waiting to devour your function calls, returning only the broken skeleton and ruptured entrails of what were once perfectly beautiful, good, honest and peace loving return values. The old ways must be locked away, and cast into the deepest fissure in the deepest depths of the ocean, where there is no chance they be rediscovered and unwittingly released on humanity.
Or, how I feel when a vendor sends documentation for their SOAP web service.
The only thing worse may be when a vendor sends documentation for their "REST" web service that is clearly just machine reformatted SOAP.
But I keep re-learning what you’re getting at, throughout my career: just keep it simple. Most things can just be simple.
That’s really well put. When I saw this I just thought, well, that’s probably a lot of complexity to save a few lines of code. And then you’ll just add those lines of code back later when you realise that the client stubs are the easy bit.
But for some stack it ain't that easy though. E.g. if you want TypeScript or SSR.
I like the logo (or icon) they have, that masquerades it as some serious haskell (or some other functional PL) related project.
If it was this easy eveyone would be using RPC all over the place for many years already, and we'd have no HTTP and no train-load of other protocols.
People are using RPC over HTTP all the time. Most backend APIs I've seen are only vaguely RESTful [1] and everyone seems to stuff much of their critical functionality in JSON RPC APIs masquerading as POST endpoints.
[1] no true scotsman and HATEOAS ¯\_(ツ)_/¯
Increasingly, the frontend is deployed hand-in-hand with the backend.
RPC is a match made in heaven for stacks where backend and frontend are deployed in-sync.
There really are only two reasons for using a RESTful/GraphQL API: providing third parties access to your data (e.g. Facebook API) or decoupling frontend and backend (e.g. Netflix uses a loosely coupled microservice architecture).
Most projects don't need either.
Non rigorously a web API is just the boundary across some service which you communicate with over (commonly) HTTP at the endpoints specified at that boundary by developers. I could write my own library that wraps those endpoints with functions that make the calls to them, in fact many libraries do just that.
What this takes care of, again kind of nicely, is dynamically and automatically generating that boiler plate as you write your API so you don't have to put in the work, but I think saying this isn't just a style of building an API is a little much.
Whether you're doing RPC, REST or whatever the boundary between your service and another service is it's API.
Though I would say that RPC blurs a lot of lines. REST is clearly a way for two programs to communicate. RPC could be seen as a way for two programs to become one distributed program by means of location transparency.
Shared objects and other systems take that a lot further, RPC is in a middle ground that is very interesting but also a little scary. Reading this description I couldn't tell you exactly what the security implications are. With their TODO list app as written, can a malicious user execute arbitrary SQL (within the permissions assigned to their user) on the server? It wasn't immediately clear to me (I'm sure a little more effort on my part could clear it up).
RPC - Remote Procedure Calls
I’m not even 30 btw
Also the author: https://news.ycombinator.com/item?id=33054242
> Author of Telefunc here. I'm glad folks are finally taking RPC seriously.
So basically, we're at SOAP again. A few more years and maybe we'll come back to Remoting?
How would you compare its benefits to something like Swagger?
How do you like the extra verbosity of the message over the wire?
Do you have a favorite generated TS client library?
About verbosity, I'm not sure what you mean because it's has lightweight as any other JSON exchange. Of course there are other protocols based on binary messages, should you need that. But it's different.
The backend language I work with is Go, so there are "two" problems that need to be solved for this to work:
- Resolving function name and encoding/decoding arguments from a url to a real function call
- Representing Go structs as Typescript interfaces for the client side code to look like regular function calls with regular types and all that.
For the second part, I have a writeup about how I'm doing it: https://hasen.surge.sh/go-ts-type-bridge.html
It's worth noting that the title of the OP website is wrong.
"Remote Functions Instad of API"
What do you think an API is? API does not stand for "HTTP Requests with JSON". It stands for "Application Programming Interface".
I don't think "API" just means "programmatic interface". It also denotes some kind of decoupling. A library API => decoupling between lib user and lib author. GraphQL API => decoupling between backend and frontend.
The point of Telefunc is precisely to not decouple frontend and backend. Telefunc is all about bringing backend and frontend tightly together.
So, the tagline is very much on point ;-).
But, yea, you make me think that "Remote Functions. Instead of REST/GraphQL." is maybe better. I'll think about it.
I.e. public access => GraphQL, internal access => RPC.
With a RESTful API you do these requests:
GET https://api.todo.com/task?completed=false
POST https://api.todo.com/task/42 { "completed": true }
POST https://api.todo.com/task/1337 { "completed": true }
POST https://api.todo.com/task/7 { "completed": true }
With RPC/Telefunc, this is what you do instead: export async function onMarkAllAsCompleted() {
await sql('UPDATE tasks SET completed = true WHERE completed = false')
}
The crux the matter is that a RESTFull/GraphQL API is a set of generic endpoints that are set-in-stone and that are designed to be able to serve all kinds of frontends, whereas with RPC you implement endpoints as-you-go that are tailored to your frontend.For example, if you want to provide third-parties access to your data, then RPC wouldn't make sense. You need an API for that.
On the other hand, if all you need is your frontend to access your database, then an API really is just an unnecessary indirection. (Although for large teams an API can be useful to decouple the frontend from the backend.)
Philosofically, there is no difference though each have their own connotations.
You expect RPCs to be much more integrated in a language and an API to run over standard transport protocols using standard data formats. However, this is isomorph.
get_tasks({completed:false})
add_task({id, …})
update_task({id, completed})
upsert_task({id, …})
delete_task(id)
Or a meaningful subset of it, also set in stone when appropriate.There is no reason to start being unreasonable with your APIs once you switch underlying protocols. And no protocol will stop you from doing
POST /sqls <some sql>
Also, pedantically, your POSTs are wrong. You have to PUT (or likely PATCH in this case) into /task/:id, or POST into /tasks.The source code of Telefunc has no known bug"
No known bugs does not "rock-solid" make. This claim alone makes this project very hard to take seriously.
https://en.wikipedia.org/wiki/Fallacies_of_distributed_compu...
RPC is back. Smarter, leaner, and stronger. (Sorry for the marketing jargon, but I really do believe that.)
Telefunc is still fairly young, you can expect a lot of polishing in the coming weeks/months. The high-level design is solid and I expect no breaking change on that end.
If you encounter any bug (or DX paper cut), please create a GitHub Issue and I'll fix it. I'm also the author of https://vite-plugin-ssr.com which also has no known bug, so I do take that claim seriously.
Let me know if you have any questions!
Edit: so far, I'm preferring trpc, because it has support for zod and a few other libraries https://trpc.io/docs/v9/router
It seems like this library has its own bespoke syntax for types https://telefunc.com/typescript
Less boierlplate.
> so far, I'm preferring trpc, because it has support for zod
What's your use case for wanting zod instead of https://telefunc.com/shield#all-types?
Telefunc should support zod, why shouldn't it? Just pass them as native zod types and all good. You could also convert them before with z.infer but you don't need to.
> It seems like this library has its own bespoke syntax for types
Only for stacks which don't transpile server-side code. You can use normal TS types with something like Next, Nuxt, Svelte, Vite, etc. So, these bespoke types aren't relevant for the majority.
I believe this is only the case with routes, and they're still statically typed. E.g. if you only define `/getUser` and try to invoke `/gteUsre`, it will yell at you.
> Telefunc should support zod, why shouldn't it? Just pass them as native zod types and all good. You could also convert them before with z.infer but you don't need to.
Can you elaborate on this? AFAIK it only supports the types listed here https://telefunc.com/shield#all-types So my understanding is that you can't pass native zod types.
What's your use case for wanting zod instead of https://telefunc.com/shield#all-types?
Importantly Zod philosophically follows "parse, don't validate" https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va... which means that once validation is done, you get a type - a parsed value. This means you can validate clientside and serverside using the same types. Again, sure you could do the same with Telefunc, but you still need to invoke Abort manually and every single RPC definition you have needs to be followed by Zod.parse. A small cost to be sure, but what are the advantages of Telefunc over tRPC? I'm not seeing any right now.
tRPC also isn't strongly tied to Zod, it also works with yup, superstruct, and custom validators.
def self.get_initial_state(initial_count: 0, **)
{ count: initial_count }
end
def handle_decrement(_)
update do |state|
{ count: [0, state[:count] - 1].max }
end
end
def handle_increment(_)
update do |state|
{ count: state[:count] + 1 }
end
end
def render
<div class={styles.counter}>
<button on-click={handler(:handle_decrement)} disabled={state[:count].zero?}>
-
</button>
<span>{state[:count]}</span>
<button on-click={handler(:handle_increment)}>
+
</button>
</div>
endHow are errors handled though? What happens when you “throw Abort()”.
Samen => Neat :-).
Maybe there has been enough changes in the ecosystem now to be able to abstract network and write code that’s not too brittle.
If you have a tightly coupled frontend and backend and no need for third party consumers of your API, I highly recommend it. Makes moving between frontend and backend such a pleasant experience with a well typed and defined interface.
The marketing rhetoric of telefunc activates my skepticism, but I hope it's just me
Why? (Author of Telefunc here.)
SOAP, RPC and CORBA.
Here we go again.
Maybe you can also pass closures around...
https://twitter.com/MontyPythonOps/status/129218356795963801...
Feel free to elaborate. I'm also the author of https://vite-plugin-ssr.com/ which indeed has no known bugs.
One negative: I don't think people realize how easy it will be to inadvertently include server side files in client side bundles.
The technical approach mitigates this and is well designed. But simply by blurring the lines it might result in sever side config bundled to the client.
(Easy to mitigate, just add a line to server side stuff which and destructs if it detects wrong environment)
The way people abuse HTTP JSON API design these days I figure it would just cut out a lot of the cruft. Maybe it's not the best way to do some things, but it might be a lot simpler...
Well that is until someone writes a recursive function (or just a loop) which calls out to an RPC without consideration. But that's nothing new either....
How is `fetch(base + '/myFn')` all that different than just calling `rpc::myFn`?
Aside from maybe being able to generate an OpenAPI spec (something that the tRPC community is working on), it's just going to fall apart outside of web apps.
But for those developers it's great for eliminating this weird step where we need to think about all our data going into a completely unstructured string (json) when going between our server and client. For most full stack JS/TS apps that's all you need.
Reeally clueless about this stuff as a newbie dev, first time hearing that
So much code is an internal client function "GetUser(5)" configured to hit a specific URL "/users/5" and the server accepts requests on "/users/5" just to end up invoking a handler called "GetUser(5)".
Definitely a fan of completely skipping the URL "REST" ceremony.
We program things to make our jobs easier. If it looks like a call, takes args like a call and returns values like a call, it probably is a call. If you have nothing against a call, you have nothing against RPC. Give me TCP, SMTP-over-SOAP-over-HTTP, XML-over-PigeonPost, whatever. I’ll hide this nonsense in an rpc.<langname> file and turn it into a call, because calls are my main programming instrument. Everything else is just an annoying noise that either takes a page to perform or gets wrapped into the exact same parametrized call.
With stacks like Next.js, the frontend and backend are deployed in-sync. This makes RPC a match made in heaven.