19 ms·
Give me /events, not webhooks
- einrealist 5y agoI am in favor of doing both: provide Webhooks (Callbacks) and Feeds. Webhooks are great as triggers. The payload can be also minimal, especially if data is sensitive and authentication / authorization is an issue. And Feeds provide data (can be static / cached, served by CDNs, optimized for batch processing in different variants) at the consumers' pace. The combination of both are ideal.
- sergiomattei 5y agoBuilding polling infrastructure is substantially more complex than setting up a GET endpoint to handle webhooks. If you need strict consistency guarantees, sure. Otherwise, don't piss off your API consumers, webhooks work just fine.
- crooked-v 5y ago> Building polling infrastructure is substantially more complex That really depends on the setup you're using. There are plenty of server platforms out there where setting up a cron is no more complicated than making a GET route handler.
- sergiomattei 5y agoI'm looking at it from the perspective of a web dev. If you're already building a web application, it is almost always more work to do the polling setup. In Python, it's either a cron script or Celery beat. In PHP, usually a cron script. That all means more processes running outside of your web framework, more stuff to deal with, more complexity. Now you have to manage e.g. running a celery process, managing crontabs wherever you deploy... Even in languages like Elixir where long-running scheduled processes are cheap and native, you still have to write a GenServer in comparison to just using your web framework. I'm fine with the approach in the article. I actually like that they're giving the option for multiple ways of getting those events. Just please, please don't make /events the only option...
- justsomeuser 5y agoI actually have the opposite opinion. I'm an experienced web developer. Setting up polling is easier for me than setting up an HTTP endpoint. I typically use a language with an event loop (async/await), so there is always something like `setInterval(poll, 500)`. All that code needs is a connection to the internet. If the server is down for 24 hours I can start it up and it'll read the missed events. I can set up 10 dev environments with just an API key difference in the config. I can batch apply events in a single database transaction, ensuring consistency. But with a webhook, I need to ensure that my server can accept incoming connections, the external API knows that location. Each dev env needs to replicate this public HTTP server set up. I need to monitor the uptime of the server closely as missing events or erroring on a subset of events could leave my database in an inconsistent state.
- masklinn 5y ago> There are plenty of server platforms out there where setting up a cron is no more complicated than making a GET route handler. Or way simpler if you're not building a web application in the first place.
- shadowgovt 5y agoIt's less about cost of building and more about cost of running. Polling is chatty when updates are infrequent.
- toomuchtodo 5y ago> If you need strict consistency guarantees, sure. Otherwise, don't piss off your API consumers, webhooks work just fine. Ahh, but all problems are queues. What happens if your webhook destination is down and your source system sending queue backs up? What happens if your destination endpoint is up, providing 200s to requests, but throwing away the data quietly due to a mistake during a rollout? Or your webhook source quickly ramps to a volume that is effectively a DoS attack? (These are all problems I encountered in a role at a low code/no code product). I strongly endorse others in this thread who indicate long polling events is a suitable pattern. You want the best worlds of data durability and consistency through polling functionality, but also as close to real time event firing as possible. Of course, some APIs you have no control over, and are stuck building robust, chatty polling infra to support because your (paying) users demand access to those APIs. Such is the schlep.
- superbaconman 5y agoWhy do I need two different ways of retrieving events? Wouldn't the data also be available via the usual rest api? If events fail on the consumer end it's their responsibility to resync. Presumably code was written for an initial sync anyway no?
- atian 5y ago> One idea for Stripe and other API platforms: support long-polling! It’s great that we’ve went full circle. But make no mistake that this only means one thing: that servers are cheaper than ever. We can now afford to entertain previously extravagant ideas.
- simonw 5y agoLong polling is a lot easier to support now than it was a few years ago, thanks to the wide availability of async server frameworks - Node.js, Python ASGI etc - which make supporting thousands of simultaneous long-polling connections with a single server much less expensive.
- deleted 5y ago[deleted]
- maerF0x0 5y agoalso the OP seems to ignore all the issues with webhooks that longpolls suffers or is worse at. eg: you'll lose all those tcp connections if your service is down -- one of the main complaints about webhooks...
- coldacid 5y agoWhich, if the parts discussed before long-polling was mentioned were implemented, wouldn't be an issue since you'd be starting from the first event following your last-recieved cursor anyway.
- deleted 5y ago[deleted]
- Anunayj 5y agoI've have had a couple issues implementing Long Polling in the past. At times I've had the firewall or reverse proxy drop client connections if it detects no data transfer. Which meant I had to timeout all the requests every 30 secons or so. Make a new request before the other one ends, and it all becomes messy. At this point, its honestly just easier to just have a websocket + events endpoint with a cusor both.
- BrianOnHN 5y agoIt's an incentives issue. Webhooks or for when the service provider is aiming for the bare-minimum functionality with the least overhead. If they have the incentive to maximize your consumption of the data, then they should offer both, and may even overnight a physical copy.
- paxys 5y agoThere are lots of reasons to want to immediately respond to an external event besides building an eventually consistent data syncing system. Polling an API endpoint works fine for the latter case, but not much else. A good platform should offer both of these and more (for example Slack does webhooks, REST endpoint, websocket-based streaming and bulk exports), and let the client pick what they want based on their use case.
- benlivengood 5y agoLong-polling is the way to immediately retrieve events. It's more efficient and lower latency than waiting for a sender to initiate a TCP and TLS handshake.
- andrewstuart2 5y agoA persistent connection has a cost. Your statement may be true in some circumstances but definitely not all. Namely, for infrequent events it is much more efficient to be notified than to be asking nonstop. Sure, the latency is lowest if the connection is already established, but for efficiency the answer is not cut and dry but is rather a tradeoff decision based on the expected patterns.
- dnautics 5y agoExactly. Perhaps an event happens once or twice-ish a day per customer, and never on the weekends.
- nmcfarl 5y agoI've got an API where an event happens once a month (+/- 2 weeks) for a large percentage of our customers.
- eptcyka 5y agoAlso, there's the case of ISP's just dropping idle TCP connections. It can also take a while to determine that a TCP connection is broken.
- candiddevmike 5y agoWhy wouldn't service providers want to offer long polling? It seems a lot easier to build (no webhook registration backend) and no retry logic/SLAs outside of your control. SSE seems so much simpler.
- judge2020 5y agoKeeping those connections open probably isn’t super cheap and complicates deploying rolling updates - you’d need to kill all connections when you update and that would require some sort of RPC (so that you only kill those existing connections after they’re done sending in-flight data).
- Nullabillity 5y agoWhy bother? Just kill them and let the clients reconnect on their own. They'll have to handle that case anyway...
- judge2020 5y agoWith polling you have to make sure you finish sending data for the current in-flight event. If you don’t then the client doesn’t receive that event, unless you also send them events from the past 30 seconds on first poll.
- Nullabillity 5y agoDon't delete the events from your queue until you receive a client ack?
- thrower123 5y agoWith some of the load-balancers and gateways and things in that space I've had to use, long-polling doesn't work at all because of short timeouts.
- paxys 5y ago> It seems a lot easier to build Quite the opposite. HTTP servers and clients are essentially a solved problem. Massive scale-out, load balancing, retries, authentication, authorization, rolling deploys etc. can all be done out of the box by a hundred different providers. Anything to do with maintaining a large number of open TCP connections is still a massive pain on the server side.
- avalanche123 5y agoI think this is also getting at the difference between pub/sub and state synchronization. While one might think they want the former, what they really want is the latter. Get some state and receive updates continuously rather than deal with unreliable stream of updates
- shadowgovt 5y agoOn HTTP, pub/sub is eventually guaranteed to drop some messages because TCP/IP itself is not a guaranteed networking protocol (it just makes some promises about failures being uncommon and probably detectable). If what you want is guaranteed state synchronization, pub/sub alone can't give it to you.
- mywittyname 5y ago> To mitigate both of these issues, many developers end up buffering webhooks onto a message bus system like Kafka, which feels like a cumbersome compromise. Kafka solves exactly the issue that the author is complaining about. This is a safeguard to ensure that data isn't dropped in the event of an issue, and provides mechanisms to replay events. The tradeoff between pushing and polling have been argued since forever. In other news, mechanics who work with bolts often do so with ratchets. This is a cumbersome compromise, just give me Torx fasteners!
- jerf 5y agoIt would if the source was pushing into the Kafka stream directly. It doesn't solve the problem of going out of sync if my code to push to the Kafka stream is entirely down and I miss POSTs. (And, of course, I don't want Kafka. I want Google PubSub. No, wait, I mean SQS. No, wait, I mean I want zeroMQ. No, I mean....)
- nine_k 5y agoThe question is: who maintains the queue of events, and pays for it? Certainly the event producer is in a better position to maintain a queue without missing events, but it also means they need to buffer more data in their queue system to accommodate for your receiver's downtime
- BasieP 5y agothis!
- toomuchtodo 5y agoYou meant Apache Pulsar! :)
- jerf 5y agoI'm feeling cosmopolitan today. I mean all the things!
- fiddlerwoaroof 5y agoIt seems to me that you could build a protocol where normal syncs happen through webhooks where each webhook event refers to the event id of an immediately previous event. If the system receiving notifications doesn’t have that event, it makes an API request for all events between the latest event it has and the one it just received.
- williamdclt 5y agoThat is pretty much what TCP does, except that it doesn't "request" missing packets: the client just acknowledges the ID of the last packet it was happy with. It requires a sequence though, so that you know that the client can know that packet it just received isn't the one it expected, but you could build that with a chain of IDs like you're proposing.
- aboodman 5y agoIt the system is moving fast this is still somewhat complicated to implement robustly because by the time the "catchup" request to t0 returns, more time has passed and more events have happened, so you still can't resume consuming the webhooks. To be correct with such a system you have to be prepared to queue the incoming webhook events, do the catchup query, then replay the queued events.
- MrStonedOne 5y agoonly if the order of events matters.
- fiddlerwoaroof 5y agoYeah, if the events can be handled idempotently and this handling properly accounts for time, you don’t have to stop processing webhooks while filling in the gaps.
- aboodman 5y agoOK but, it usually matters. If the events represent changes to some object, those changes almost always have to be handled in order if you are to arrive at the same end state as the source. edit: Also, idempotent is not the right term here. Idempotent just would mean the event could be handled by the receiver multiple times w/o changing the meaning. If you need the events to be applicable out of order, then you need them to be commutative. This is a much more difficult property to ensure and in practice, I am guessing, almost non-existent in deployed webhook APIs.
- tlarkworthy 5y agolong polling is not good for serverless consumers. webhooks are great for compute on demand so we should work towards that (it's cheaper coz it's more effecient). You do not need storage in the producer AND in the consumer, you just need a queue in the producer. Yes, even that is annoying, but the suggested architecture will still lose data if the long poller is down unless there is storage in the producer... so nothing significant has really been solved
- kureikain 5y agoI think with a right a strategy for retry then webhooks are great. On my email forwarding app https://hanami.run https://hanami.run we offer both method to give user access to their email: 1. webhook with retry up to 7 days. 2. a REST api to fetch all data Sending webhook out properly require lots of effort, especially idempotent key concept to avoid duplicate data. And control concurency to avoid swarming the webhook endpoint. So at the end of day, both are require same amount of resources, either on the sender side or the receiver side.
- leowoo91 5y agoIt just depends which side you would like to put the responsibility on. Webhooks is mostly for owning it at source.
- mbrevda1 5y agoAre events and webhooks mutually exclusive? How about a combination of both: events for consuming at leisure, webhooks for notification of new events. This allows instant notification of new events but allows for the benefits outlined in the article.
- saurik 5y agoYeah... I'd go so far as to argue that this is the only architecture that should even ever be considered, as only having one half of the solution is clearly wrong.
- sb8244 5y agoWhat about supporting fast lookup of the event endpoint, so it can be queried more frequently? I think that a combo of webhooks / events is nice, but "what scope do we cut?" is an important question. Unfortunately, it feels like the events part is cut, when I'd argue that events is significantly more important. Webhooks are flashier from a PM perspective because they are perceived as more real-time, but polling is just as good in practice. Polling is also completely in your control, you will get an event within X seconds of it going live. That isn't true for webhooks, where a vendor may have delays on their outbound pipeline.
- jacobr1 5y agoThe article advocate for long-polling
- sb8244 5y agoYea, you're right. I am reading the advocacy as "if you need real-time, then support long-polling." I see the value in this, but I actually disagree with the article in terms of that being the best solution. Long-polling is significantly different than polling with a cursor offset and returning data, so you wouldn't shoe-horn that into an existing endpoint.
- pak9rabid 5y agoCouldn't keeping a request open indefinitely open the system up to the potential of DoS attacks though? Correct me if I'm wrong, but isn't it kind of expensive to keep HTTP requests open for an indeterminate amount of time, especially if the system in question is servicing many of these requests concurrently?
- keeganj 5y agoFor infrequent events, why not both? A webhook to push the event and a full list at /events?
- qwertox 5y agoI definitely don't want to see long polling. In that case I'd prefer a combination of /events and websockets, where websockets can push (or pass via a GET param) the last read event from /events to notify the server which is the last known event.
- airstrike 5y agoTFA addresses this by suggesting long-polling as an option rather than the only way to request `/events` > In our integration with Stripe, it would be neat if we could request /events with a parameter indicating we wanted to long-poll. Given the cursor we send, if there were new events Stripe would return those immediately. But if there wasn't, Stripe could hold the request open until new events were created. When the request completes, we simply re-open it and repeat the cycle. This would not only mean we could get events as fast as possible, but would also reduce overall network traffic.
- grejdi 5y agoWebhooks are great for producers of events, and I'd argue that it's too cumbersome for them to provide an '/events' endpoint primary because of scaling. With webhooks, they can offload events at their own pace. For consumers, I agree with most here that Kafka is certainly overkill. We've gotten away with a very simple architecture to have reliable event consumption. We point all webhooks to an (AWS) API Gateway backed by Lambdas. The Lambdas push the events to an SQS queue (FIFO-queue, if it needs some sort of sequence), and we take our time consuming the events through a very generic poll.
- masklinn 5y ago> Webhooks are great for producers of events, and I'd argue that it's too cumbersome for them to provide an '/events' endpoint primary because of scaling. With webhooks, they can offload events at their own pace. TBF they could do something similar with `/events`, instead of pushing events to a webhooks-sending queue just push them to the events buffer, which could even be a circular buffer just to point out that the essay is completely wrong. TFA is not asking for /events, they're asking for a very specific kind of /events with a large non-drained buffer. Something which would only ever work for low number of events: $dayjob's github integration takes in several events per second. A proper event stream would be nice though, github's webhooks delivery system is not exactly reliable.
- jcrites 5y ago> With webhooks, they can offload events at their own pace. They can't offload webhooks at their own pace if the two parties want reliable delivery. The server providing the webhook might be experiencing a prolonged outage, in which case the sender needs the ability to buffer the events anyway.
- supergeek133 5y agoWorking in IoT land, we rely quite a bit on EventHub/AMQP type delivery for events to say a 3rd party (e.g., Alexa/Google/Etc). That being said, I've also lobbied for a similar endpoint so I don't get support tickets for "missing data". Both? Both are good.
- recursivedoubts 5y agowhy not both?
- freedomben 5y agoThis is just my opinion of course, but I've consumed a great number of APIs and I love when there is. You don't even need /events as long as there's a good index endpoint for the object in question. For a great number of applications it's not that big of a deal to miss a webhook, and the extreme simplicity that it gives the developer is worth a great deal. With how enormously complex a lot of systems have gotten, I really favor simplicity whenever possible.
- graton 5y agoMakes me think of how the OpenStack project watches for events to Gerrit. They open an SSH connection to the Gerrit server with the stream-event command. It then stays connected to the Gerrit server and all the events that occur show up in the stream and the program can take actions based on the events it sees. Gerrit stream-events doesn't solve the issue if the connection is dropped and events occur while disconnected. I personally (for my hobbyist use case) would prefer the article's /event system over webhooks as webhooks require you have a system that is available on the Internet to receive the webhook. Where having this /event system would not require that.
- polote 5y agoThe article is interesting but is misleading. What the article really says, is that if in average you receive a webhook every second or faster, it is better to poll every second an /events endpoint. Well the best advantage of Webhooks over polling is that you receive events straightaway no matter the volume of events. If you already know the volume and the volume is high, of course polling is going to be better for everyone.
- skybrian 5y agoIf the webhook just triggers a download from /events then both can be made idempotent. If you miss an event then you can get it later.
- abnercoimbre 5y agoI like having a one-off command-line app triggered by a webhook. If you miss an event, invoke the app manually. If you pass it the same event twice it won't matter (idempotency!)
- maerF0x0 5y agoIMO the real solution is give me a better transport that RESTful HTTP! As many others have pointed out things like Kafka are built for these kinds of usecases. So often I see people trying to design around the flaws in REST while ignoring that we've had some pretty good progress in the ensuing 20yrs.
- himoacs 5y agoAh, I hear that a lot from customers I work with. A true event-driven system requires both events and webhooks. You will always have apps that only interact via REST so you can't really use streaming architecture here but you can make them more real-time via webhooks. The article talks about issues with webhooks such as not being reliable if the service goes down and messages are lost. It also talks about developers daisy-chaining multiple services together to put forward a solution which is not robust. That's why you need a broker that does event distribution, supports multi-protocols (REST, AMQP, MQTT, WebSockets...) natively without any proxies and supports Webhooks. You can push messages to your REST clients and if they disconnect, the messages will pile up in a queue, ready to be consumed when the client reconnects. Solace PubSub+ Broker does all of this. Disclaimer: I work at Solace.
- historyloop 5y agoI tried skimming through the article to attempt and derive the missing elevator pitch, but I saw them reimplement precisely the system they maligned at the start (push notifications with polling). Did anyone here understand what their value proposition even is?
- aboodman 5y agoDid you check the website? The value prop is incredibly clear: they give you a Postgres database you can query with SQL rather than having to either (a) learn and code to a custom API or (b) setup your own sync system to get that Postgres db.
- historyloop 5y agoI'm talking about the elevator pitch of their blog post, not of their company. Which are actually two distinct things (they're not describing their service in this blog post).
- fart32 5y agoLong polling doesn't scale very well. Webhook/websocket and events endpoint combined sounds like the sweetspot to me.
- lxe 5y agoHolding requests open for long polling is probably difficult to scale. How do you persist connections when application servers drop in/out? How do you load-balance? What about socket descriptor limits? etc...
- z3t4 5y agoSomething that is underestimated in messaging systems are incremental numbers, eg. add + 1 for each message, so the receiving end get 1,2,3,4,5,6 etc, and if it then get 8 it knows it missed the 7th message. And it will know if the messages are out of order. And it can pick up if it goes down by requesting the missing messages.
- Redsquare 5y agoOr put simply, a sequence number!
- the_linux_lich 5y agoDude, just use a timestamp.
- z3t4 5y agono... time is relative! (no pun intended) - sending messages to the space station or a satellite in orbit would be off, or a moving,train, or a tall building... Did you know there are leap-seconds, just like there are leap-year? and atomic clocks are not yet standard on server/PC's, what is standard though is a time-client that will change the computers clock at some random intervals depending how much drift it has. A sequence number is also easier to parse.
- mrkurt 5y agoWe have (almost) the opposite problem, webhooks are too synchronous for what we need to ship to people. We're experimenting with giving people a NATs endpoint to listen for logs and other events: https://community.fly.io/t/fly-logs-over-nats/1540 https://community.fly.io/t/fly-logs-over-nats/1540 Having an ephemeral messaging system and a ledger to reconcile against is a nice, simple way to provide immediacy and eventual consistency (where eventual could be days). It's a pattern we're using all throughout our infra.
- joelcollinsdc 5y agoWe have this problem too. When we send a request to create an entity in an external system, before we get the response back with the entity Id, we already have received a webhook saying said entity was created. Makes a basically trivial workflow quite confusing.
- rkalla 5y agoFWIW, this is what CouchDB has done from Day 1 and it _always_ seemed like one of the most magical and surprising things tool or platform providers would suddenly realize and then LOVE about using the DB. There was nothing fancy about it, you could just listen to an endpoint and it was a stream of the append only log of events occuring in the DB to the point that you could literally use it to feed a replicated master or slave (or backup). I imagine your use-case is a bit more nuanced, but I sure do love that model.
- deniska 5y agoI'm building integrations with various marketplaces at a company I work at (fulfilled by seller kind of deal), and I can confirm, it's much easier for us to schedule an HTTP request once in 15 minutes than to create a custom HTTP service responding to specific requests from 3rd parties. We're in the business of selling things, we're not in the business of building HTTP services. Our ERP-like thing is down for maintenance from 10pm to 11pm, so we can't use it as a platform for responding to webhooks. I'll hack something together in a pinch when it's the only way to get orders from a marketplace service, but then eventually I'll have to explain to my colleagues how to linux, how to HTTPS, how to python, how to WSGI, and all other stuff our company typically doesn't do, but has to do now, because this particular marketplace wants to POST orders to us.
- boring_twenties 5y agoJust curious, how would you prefer to receive these notifications?
- deniska 5y agoBy polling an endpoint provided by the marketplace with parameters "since" and "to" to filter events by the time they happened. We typically set "since" to two days ago and "to" to tomorrow. We're not in the hurry, we have an hour or two of leeway between receiving a message and having to act on it. I certainly prefer the polling solution for that usecase. Easier to set up, easier to debug, easier to notice that something is wrong.
- dceddia 5y agoMaybe there's an opportunity here for some kind of buffering service that would receive webhooks and present them as a stream of events. Or maybe something like this already exists?
- boring_twenties 5y agoI was thinking the same thing, it's kind of why I asked the question. :) On the one hand, it seems like something too simple to expect people to pay for. On the other, it's so simple it wouldn't be a huge loss to try it out and see if they will.
- bkrausz 5y agoI was responsible for Stripe's API abstractions, including webhooks and /events, for a number of years. Some interesting tidbits: Many large customers eventually had some issue with webhooks that required intervention. Stripe retries webhooks that fail for up to 3 days: I remember $large_customer coming back from a 3 day weekend and discovering that they had pushed bad code and failed to process some webhooks. We'd often get requests to retry all failed webhooks in a time period. The best customers would have infrastructure to do this themselves off of /v1/events, though this was unfortunately rare. The biggest challenges with webhooks: - Delivery: some customer timing out connections for 30s causing the queues to get backed up (Stripe was much smaller back then). - Versioning: synchronous API requests can use a version specified in the request, but webhooks, by virtue of rendering the object and showing its changed values (there was a `previous_attributes` hash), need to be rendered to a specific version. This made upgrading API versions hard for customers. There was constant discussion about building some non-webhook pathway for events, but they all have challenges and webhooks + /v1/events were both simple enough for smaller customers and workable for larger customers.
- alexgartrell 5y agoI think the Stripe API stuff you did was fine, but you really did your best work as a concepts of mathematics TA.
- AtNightWeCode 5y agoThis is a fake post? Never encountered this level of incompetence in real life.
- spullara 5y agoPretty easy for a customer to setup an SQS queue and a lambda for receiving them rather than rely on their infrastructure to do all the actual receiving. Way more reliable than coupling your code directly to the callback.
- jon-wood 5y agoThis is precisely what we do where I work. We have a service which has just one responsibility - receive webhooks, do very basic validation that their legitimate, then ship the payload off to an SQS queue for processing. Doing it this way means that whatever’s going on in the service that wants the data, the webhooks get delivered, and we don’t have to worry about how 3rd party X have configured retries.
- klysm 5y agoThis seems like another instance of the never ending war of push vs pull
- bno1 5y agoA pattern that I like to use in toy projects is to have an events endpoint and just send the newest event cursor through a notification channel (e.g. webhooks) when a new event occurs. You get new event quickly, you don't have to keep connections open for long-polling, and you can keep polling with a low period in case the event channel stops working for some reason.
- closeparen 5y agoI have long felt there is a startup opportunity for a service that receives webhooks and lets you subscribe via message queue.
- pmlnr 5y agoBasically: RSS for anything.
- raksoras 5y agoOne of the complexity of the polling approach on a consumer side is having a long running poller. This is trivial to do in Java apps - start a polling thread - but not so straight forward in case of PHP apps, for example. In that case you'd have to setup a cron job or a separate polling script under some sort of process supervisor like systemd to poll periodically/continuously. I wonder if the two approaches could be combined to simplify things for consumer apps at the cost of slightly more complexity on the producer side? Instead of POSTing the actual event data to webhook, the producer just uses consumer's webhook to "poke" it - to tell the consumer app "hey, you have new events waiting for you". On receiving the poke the consumer endpoint handler/PHP script can just turn around and do a GET to "/event" with anything > last downloaded event id query. That way you don't have to support long polling on the producer's servers and it's not a big problem if consumer misses couple of webhook "pokes". The next time it does receive a webhook "poke" successfully, it will download all the events and be all caught up. If real time notifications are not strictly required then producer side can even run the webhook dispatching code on a scheduled basis to coalesce multiple events in a single "poke" to a consumer to be more efficient, if desired.
- tlarkworthy 5y agoThis article is premised on the incorrect strawman that webhooks are complicated because the consumer has an extra persisted message bus. But if the producer retries and the consumer does not respond with 200 until it has processed the message, no consumer side message queue is needed, the consumer can rely on the producer to reach at-least-once delivery. In both cases (webhooks and /events) storage is needed producer side, so nothing consequential has changed, only with /events you need long lived TCP connections which ties up (e.g. you can't do this on FaaS endpoints) Functions as a service are absolutely ideal for low frequency webhook receivers. SO SO SO cheap.
- coder543 5y ago> But if the producer retries and the consumer does not respond with 200 until it has processed the message, no consumer side message queue is needed, the consumer can rely on the producer to reach at-least-once delivery. Part of the point of the article was that you may deploy bad code which returns 200, but doesn't actually take the correct action with the events, and then you have lost all that data and have no way to get it back, which is why you have a consumer-side message bus to hold the webhook history, so that you can replay the webhooks if you made a mistake. Your comment does not address this at all. If the service exposes a /events page, and especially one that supports long polling (or SSE), then you no longer need a consumer-side message bus, and you might not even need webhooks at all. I definitely think webhooks should be offered, but I agree with the article that webhooks shouldn't be the only thing.
- villasv 5y agoThe article specifically exemplifies the case of the web hook having faulty code (introducing nulls) while still not failing with errors. In this case if you don’t have storage on the consumer side, you have to ask for the producers to be merciful gods.
- ezekg 5y agoIn this case, you can simply replay the badly handled webhooks. No need for long-polling.
- rad_gruchalski 5y ago> If the follower goes down, when it comes back it can page through the history at its leisure. There is no queue, nor workers on each end trying to pass events along as a bucket brigade. Sure, there is no queue. There is an append only log. Kafka is not a queue but an append only log. I do not like the proposed solution. I do not like it because it assumes that I have to maintain the infrastructure to do all the distributed logging on my end. As in, most likely I have to maintain a Kafka cluster. There’s also one thing glossed over in this article. What if your consumer went past certain messages but it mishandled them? You can go to the past either. If your consumer needs ordered delivery, web hooks might not be the best solution, indeed. But it might cost you more because I need additional infra to provide you with that.
- danudey 5y agoMy company has recently switched to Microsoft Teams, where unsupported integrations happen via webhooks. For example, if we wanted to be able to trigger builds in Jenkins or Gitlab, or acknowledge alerts via AlertManager, we'd have to set them up as webhooks to the appropriate service. The problem is that all of those services are internal to our network, and aren't accessible from the outside world. We cannot set up a webhook to Jenkins because Jenkins does not have a publicly accessible URL. We cannot set up a webhook to Gitlab, or to Prometheus, or to Sentry, or anything else, because those are all internal services. The only option there would be to create a new, public-facing server, set it up with a domain name and SSL certificate, expose it to the world, and then give it access to those services - which defeats the point of having those services internal and secure if we just create a non-internal system and give it access to them. Alternately, we have that new, public-facing server buffer those requests and have other services poll them, somehow, so that it cannot connect in, but now we're getting into the same situation as described in the article. If there were an API, I could easily create a small daemon that would watch for events and dispatch them accordingly, and then respond to them as needed; instead, my only option is to build some kind of Frankenstein - or to give up entirely, which is the more reasonable solution. Then again, this is Microsoft Teams, where creating an application requires an Azure account and jumping through a ton of hoops, so they're no stranger to stupid ideas that no one wants to deal with.
- iamtheworstdev 5y agocheck out https://smee.io/ https://smee.io/
- graton 5y agoYou have the same sort of issue that I do. You might look into Cloudflare Tunnel (formerly Argo). It is free and allows you to poke a hole in your firewall to a specific service. If that meets your security requirements. https://www.cloudflare.com/products/tunnel/ https://www.cloudflare.com/products/tunnel/
- fidesomnes 5y agoA similar idea from a hn member https://tailscale.com/ https://tailscale.com/
- cryptonector 5y agoYES PLEASE. Give us a GET on /events with support for hanging GETs. A hanging GET is where you get chunked encoding (which is the only option in HTTP/2 anyways) and possibly never-ending stream. I've implemented a (proprietary, for now) "tail -f" over HTTP that does this when Range: bytes=0- (i.e., end offset not specified), completing the transfer (i.e., final, empty chunk sent) only whenever the file is removed or renamed away. You'll want to add a heartbeat to any hanging GET /events.
- cryptonector 5y agoMy little tail-f-over-http server is for plain files, but this scheme works for anything. Of course, if you can output an indefinite stream (e.g., PG NOTIFYs, build logs, etc.) you can redirect that to a file and then serve up that file.
- dgudkov 5y agoI think the author is fighting the wrong problem. Webhooks are a notification mechanism first of all, not a data transfer protocol. You can view it as a control plane which can be mixed or not with a data plane. What they offer is a data plane and it makes sense. Although, it doesn't contradict the idea of webhooks, but rather complements it. A consumer can get notified via a webhook when new data is available. Whether the data itself comes with the webhook, or is available via an additional API request, is a matter of design. Personally, I like the idea of separating the control plane from the data plane. However, in some cases it can be an overkill.
- throwaway290232 5y agoThe premise of this post is wacky. They're trying to argue for how web applications should provide consistency to operations on remote systems. You know what that's called? Distributed Computing. I don't know if you know this, but Distributed Computing Is Hard. You can't solve it with a new interface or polling really fast. Webhooks are perfectly fine for what they're intended, which is inconsistent push-based notifications to loosely coupled web apps. If you require "consistency", you supplement with polling and queues and other junk. If you require real consistency, you must use a distributed consensus algorithm.
- MrStonedOne 5y agodistributed consensus/distributed computing appies for mutual/full-duplex/two-way systems, syncing changes one way from a 3rd party is not distributed computing, and not something you would want to throw a distributed consensus algorithm at
- justsomeuser 5y agoThe Stripe `/events` endpoint is kind of like a Stripe-internal webhook with a cache of 30 days. One issue is that webhooks and HTTP clients can be pinned to a version, but the events listed at `/events` are whatever the Stripe account default version was at the time of the event creation. So all of your code clients polling `/events` needs to ensure it can handle many different versions. Another issue is that child lists are limited to 10 items, which means that you need to do a direct download to get list items > 10. This means the event list is lossy as items > 10 are never contained in the event stream. Stripe feature request: - An option to include all list items. - `/events` that can be version-pinned / contains events with the same API version.
- FpUser 5y agoI have the same thing in my backend. The backend has main business server that among the other thing has an API endpoint one can query for a list of events in date-from - date-to fashion. I dismissed the idea of webhooks right at design stage as to me it looked like a minefield choke full of potential problems.
- rakoo 5y agoHistory does repeat itself. All of those issues, and the solution, are the reason CouchDB is modeled the way it is: there's a single endpoint that gives you _all_ events happening in the database, in chronological order, with both document ids and "feed" ids, reachable with long-polling. All of this more than a decade ago already.
- toomim 5y agoThere's a much better approach than /events or webhooks: add synchronization directly into HTTP itself. The underlying problem is that HTTP is a state transfer protocol, not a state synchronization protocol. HTTP knows how to transfer state between client and server once, but doesn't know how to update the client when the state changes. When you add a /events resource, or a webhooks system, you're trying to bolt state synchronization onto a state transfer protocol, and you get a network-layer mismatch. You end up with the equivalent of HTTP request/response objects inside of existing HTTP request/responses, like you see in /events! You end up sending "DELETE" messages within a GET to an /events resource. This breaks REST. A much better approach is to just fix HTTP, and teach it how to synchronize! We're doing that in the Braid project (https://braid.org https://braid.org) and I encourage anyone in this space to consider this approach. It ends up being much simpler to implement, more general, and more powerful. Here's a talk that explains the relationship between synchronization and HTTP in more detail: https://youtu.be/L3eYmVKTmWM?t=235 https://youtu.be/L3eYmVKTmWM?t=235
- derptron 5y agoThe website seems to be crammed into the left side of my screen unnecessarily.
- top_kekeroni_m8 5y agoCentering a div is hard!
- hnbad 5y agoNot really. They could have slapped a `margin: 0 auto` on that div they decided to set a `max-width` on and called it a day.
- wruza 5y agoYou may send POST /events instead. It also breaks “REST”, which is just a sort of obsession rather than a requirement here, but more importantly it wouldn’t break idempotence and proxy caching that GET implies. Edit: from the network point of view, it’s either call-back or a persistent call-wait/socket, or polling. The exact protocol is irrelevant, because it’s networking limits and efficiency that prevent everyone from having a persistent connection to everyone. A persistent connection can’t be much better than any other persistent connection in that regard, and what happens inside is unrelated story. Or am I missing something?
- tabbott 5y agoZulip's API is built on roughly this design pattern: * https://zulip.com/api/real-time-events https://zulip.com/api/real-time-events * https://zulip.com/api/register-queue https://zulip.com/api/register-queue * https://zulip.readthedocs.io/en/latest/subsystems/events-system.html https://zulip.readthedocs.io/en/latest/subsystems/events-sys... We use this same long-polling based /events API interface for all official clients (web, mobile, terminal), our interactive bots ecosystem (https://zulip.com/api/running-bots https://zulip.com/api/running-bots), and many integrations (E.g. bridges with IRC/Matrix/etc.). We also offer webhooks, because some platforms like Heroku or AWS Lambda make it much easier to accept incoming HTTP requests than do longpolling, but the events system has always felt like a nicer programming model. (Zulip's events system was inspired by separate ~2012 conversations I had with the Meteor and Quora founders about the best way to do live updates in a web application).
- Arathorn 5y agoMatrix has the same, except we call it /sync these days rather than /events, and it long-polls :)
- cultofmetatron 5y agoI love webhooks! I recently had to work with an api to integrate a card reader terminal. The system was intended to work with an on premise pos so it was oriented around events sent back and forth over a websocket. Only one was allowed per restaurant. In the end, I had to build a distributed cluster that managed a pool of processes that each spun up a websocket connection and relayed it to our pubsub system. Luckily I built out system in elixir so it was pretty easy to spin up hoarde but this would have been extremely difficult in any other language. By contrast, a webhook is easy to scale from ANY language. Just make a http endpoint. Those are way easier to scale than a stateful process. Not being able to replay a webhook event is an issue with the publisher of the webhook. not a consumption issue.
- adnanh 5y agoYou could use Hookdoo[0] or Hookdeck[1] as a replayable buffer / log :-) [0] hookdoo.com [1] hookdeck.com
- charles_f 5y agoWhat about websockets, which implement a server -> client eventing channel without having to create a construct like a polling mechanism?
- XorNot 5y agoThis is a hill I find myself frequently fighting (and losing on): webhooks are terrible to maintain, because they start from the premise "this never breaks" and thats about where development in an organization stops. The only event API I ever want is notifications there's new data, and then an interface by which I can query all new data which has arrived by some sort of index marker - because this is fundamentally reliable. It means whatever happens to my system, I can reliably recover missed events, skipped events, or rebuild from previous events. And this is in fact exactly how something like Kafka actually works! Complete with first-class support for compacting queues to produce valid "summarized" starting points. Any streaming system essentially should never start as a streaming system - it should start as a slow-path pull-based system, and have a fast-path push system added on top of it if needed - because then you've built your recovery path already, rather then what happens way too often which is just "oh yeah, we'll develop that when it breaks".
- sroussey 5y agoI agree. A simple ping with the latest ID (which is option for you to use to get events from last ID to newest ID). The go get the events, which is a likely reusing code. Polling is crap. Extra points for being able to set something like 1s between pings (now you see why I like the option ID for a range).
- delusional 5y ago> Any streaming system essentially should never start as a streaming system - it should start as a slow-path pull-based system, and have a fast-path push system added on top of it if needed - because then you've built your recovery path already, rather then what happens way too often which is just "oh yeah, we'll develop that when it breaks". I think this is a quite interesting and important point. When we talk about "doing the simple thing first" too often we end building something that is technically simple but fickle. The trick to making the simple thing reliable is to figure out which part is the slow-path (or failure mode), and then only building that. Unfortunately, it often means out result ends up technically "boring" since all the interesting optimizations are what we cut out, but I think that's worth it if the end result is a more useful product. It's something I've been working with and thinking about for a while. I think it applies to a way broader scope than this discussion.
- itsbits 5y agoHow easy will it be to reset cursor position by request via `/events`? Can it also takes input with which it can reset else just use the position?
- senden9 5y agoThe Telegram bot API supports webhooks and long running /event calls. Because Telegram bots often have no web UI events has also the plus point of allowing to block every incoming connection with a firewall. Also so DNS name or static IP needed! This is a huge helper for me personally.
- hardwaresofton 5y agoFor developers/engineers who have never seen it, SSE is a nice way to get going with streaming (slightly different from long polling, it's server-push) easily -- there's no need to jump to tools like websocket/gRPC streaming if you don't need to: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#sending_events_from_the_server https://developer.mozilla.org/en-US/docs/Web/API/Server-sent... Obviously long polling will work in more places but SSE is great if the server side needs to do the pushing. Also for syncing stripe in particular you might want to check out the work done by Supabase (still experimental): https://github.com/supabase/stripe-sync-engine https://github.com/supabase/stripe-sync-engine
- bosky101 5y agoi think eventually system of records should be able to directly push to well authenticated queues. we are a data and cpu intensive API - and moving from an client-request flow - to pushing to an API to get a pending response, then hitting their queue/webhook once the data is ready. Eventually i think only-once semantics found in kafka, other stream processing will become the norm and better alternative to webhooks, with the right security constructs. giving write access to partners to a queue or even database connection to directly push data, may sound suspect today, but be common practice in a few years.
- dotdi 5y agoI agree that webhooks have their problems, but, as somebody maintaining software that uses long-polling heavily, I will say that long-polling is quite difficult to handle reliably "over the internet". ISPs have very different views on how long a connection is allowed to be kept open, and will absolutely kill long-polling connections without remorse. This extends beyond ISPs, too. Practically all network infrastructure between API consumer and API will have to accommodate long TCP connections, which is unfortunately not as trivial as it sounds. The next cool feature of long-polling is that the server might not know that the connection is broken until it actually tries writing to it, so if the back-end relies on having or not having a connection, this will make for some interesting edge-cases. Load-testing products using long-polling also has interesting implications, such as hitting the "65k" problem on test clients and network infrastructure. Add another layer on top (or below, like Kubernetes, OpenShift, whatever) and you should be getting a prescription for anti-depressants from the very beginning, because you WILL need them.
- webmaven 5y ago> Add another layer on top (or below, like Kubernetes, OpenShift, whatever) and you should be getting a prescription for anti-depressants from the very beginning, because you WILL need them. I guess this is the current zeitgeist's version of "stock up on $PAINKILLER" or even "keep a bottle of $LIQUOR hidden in the bottom drawer of your desk".
- qubyte 5y agoOne pattern I like to use is to have a regular /events endpoint, which works for polling. The endpoint also checks the accept header though, and if it sees `text/event-stream` it'll act as an EventSource endpoint. EventSource is also nice because you can add cursors, so if the connection drops the source naturally catches up when the connection is re-established. While the interface is browser oriented, there's no reason not to use it in other contexts.
- bullen 5y agoI agree that long poll is better than websockets, but even better than long poll is comet stream = the long connection sends chunks when events occur.
- sudhirj 5y agoI find myself thinking about the often for any kind of distributed system, and here’s the rule of thumb: pulling events / polling works 100% of the time but is inefficient, and webhooks work 99% of the time but are more efficient. Make the even ingestion job idempotent, so it can handle multiple receives, then hook up a pull / poll every 5 minutes or hour or whatever to start at the last pulled date (very important, don’t start at 5 minutes ago or you’ll miss downtimes). Then optionally set up webhooks or a push model.
- xg15 5y agoWhat I don't quite get: This is all about server-to-server communication anyway, so no browsers or web platform limitations are involved. So why bother with HTTP at all and then add complexity to implement real-time event streaming on top of it? Why not simply offer e.g. a public STOMP endpoint?
- calineczka 5y agoCan anyone comment on how to do it without race conditions? I described the problem here: https://github.com/RailsEventStore/rails_event_store/issues/106#issuecomment-328287063 https://github.com/RailsEventStore/rails_event_store/issues/...
- AlfeG 5y agoAt SurveySolutions we ended up with using shared lock during events readout from postgres. This solution is not the best, but good enough for us. https://github.com/surveysolutions/surveysolutions/blob/5bc9897c6e6eba4c9a8bb17bde7c3746e3f63b6c/src/Infrastructure/WB.Infrastructure.Native/Storage/Postgre/Implementation/PostgresEventStore.cs#L239 https://github.com/surveysolutions/surveysolutions/blob/5bc9...
- calineczka 5y agoThanks for answering, I appreciate. I found good documentation in https://mariadb.com/kb/en/lock-in-share-mode/ https://mariadb.com/kb/en/lock-in-share-mode/ but I am not sure how it works in Postgres: https://www.postgresql.org/docs/9.1/explicit-locking.html https://www.postgresql.org/docs/9.1/explicit-locking.html It says "This mode protects a table against concurrent data changes" but it does not elaborate how. Is it similar in consequences to what MariaDB describes?
- AlfeG 5y agoBasically Postgres SHARE lock will ensure that there is no active transaction in this table before executing query over table. This is a table wide lock and as I said it's not a best solution, as it will slow down a bit other events producers/consumers. In our case - active data export process, will slow down a bit main application while reading new events. Best solution would be using external tool to handle streams, like Event Store, Kafka or new RabbitMq Streams. But we prefer to stick with Postgres.
- fiznool 5y agoOne of the nice things about a pull-based model (polling) is that you are in control of throughput. Need to process events more slowly? Increase the polling interval. It’s impossible to achieve the same thing with push-based (webhooks), you are at the mercy of the producer’s rate of webhook delivery. I had this issue a few years ago with a queue-as-a-service that sent jobs via webhook - the queue would intermittently drain extremely quickly, sending thousands of requests per second, which totally overwhelmed our poor single Heroku dyno. One big issue with the pull-based model though is with concurrency. If you have multiple workers polling an API endpoint for new data, you need to synchronise the ‘last seen’ ID or timestamp across all workers. Otherwise, worker A and worker B might pull the same data and you could end up with duplicates. There’s no silver bullet here, either model requires work to harden against edge cases.