13 ms·
Creator of Phoenix here. I'm happy to answer any questions folks have about LiveView, Phoenix, or Elixir in general. We've had some big LiveView features land r
by chrismccord 5y ago
Creator of Phoenix here. I'm happy to answer any questions folks have about LiveView, Phoenix, or Elixir in general. We've had some big LiveView features land recently with uploads and HEEx so now's a great time to jump in!
- ashton314 5y agoHey Chris! First, a huge thank you for making this. I started playing around with LV v0.2 or something. It's definitely come a long way since then! I've read the blog post about getting 2 million concurrent connections on a single server with minimal tuning. That's pretty mind blowing. How does that compare will real-world scalability with LV? Like, can I actually have 2 million people looking at a LV simultaneously? I think the worry I hear most is whether or not LV scales. I've personally never run into any problems at all, but the projects I've built with LV haven't been the highest-traffic apps.
- chrismccord 5y agoMy pleasure! LiveView is built on Phoenix channels, so it has the same scaling characteristics of a channels application. We had 2 million connections, but what that means is those 2 million websocket connections each started a channel to join the chat room, so we were running full-blown channels in that load test. For LiveView, the main consideration will be memory usage since you are likely to keep more state than something offloading some state to a JavaScript or native UI. That said, check out our docs on `temporary_assigns`, which allows you to specify which template state you hold on to, and which you only need the first time and can throw away (or fetch on demand) later. The other thing to consider load-wise is the very state that you can now keep in memory allows you to reduce system load. Instead of fetching and authenticating the current user for every interaction, you do that one time for the lifetime of the visit. Database load is drastically reduced and you don't spend CPU cycles doing token verification. So while there's a cost to holding state, in general this will allow you to do much less work than a stateless application.
- giancarlostoro 5y agoI’m in love with LiveView havent done much Elixir yet but I do Django and have done ASP .NET in the past. I think its a brilliant concept. The only thing kind of holding me back on using Phoenix with personal projects and ideas is really the authentication stuff not being built-in (or when I looked I got this impression). I’m curious do you ever see Phoenix being fully supporting all the vitals or was your decision not to include authentication based on modern approaches differing like JWTs and such? Curious I am definitely going to use it in the future. As a backend nerd I always held love for Erlang and I think Phoenix / Elixir are my real way into the ecosystem.
- ashton314 5y agoThere's been some progress on this front, I believe: - https://hexdocs.pm/phx_gen_auth/overview.html https://hexdocs.pm/phx_gen_auth/overview.html
- chrismccord 5y agoThe Phoenix 1.6 release candidate has been out for a few weeks, and we now include a `phx.gen.auth` generator for a fully bootstrapped authentication solution: https://hexdocs.pm/phoenix/1.6.0-rc.1/mix_phx_gen_auth.html https://hexdocs.pm/phoenix/1.6.0-rc.1/mix_phx_gen_auth.html
- giancarlostoro 5y agoNice! I'm glad to see this, I'll definitely see about trying this out soon then. So I guess its really just a matter of time while Phoenix grows. Although from what I've seen it seems to have everything else I need.
- foofoobar 5y agoThanks for your work, this really looks promising! One question I keep thinking about. What if I want to still use React on the frontend, does it still make sense to use Phoenix for the backend then or am I throwing all benefits over board then?
- chrismccord 5y agoPhoenix is still fantastic for JSON and GraphQL apis. In fact, with GraphQL subscriptions, it's extremely well suited because how well we handle WebSockets and pubsub. The community has a robust GraphQL toolkit which works with Phoenix. It has long been 1.0 and has had a book published around it, so quite solid: http://absinthe-graphql.org http://absinthe-graphql.org
- ketzo 5y agoAs a personal testament: I did this for a side project, and it worked perfectly. Phoenix does very well as "just" an API/backend environment.
- ethnt 5y agoThanks for your work! One question I had is about when it comes to expanding beyond the web, what are the solutions available with Phoenix? For example, if I'm making a web app using LiveView, do I need to make a second app for my API for an iOS app?
- spiderice 5y agoI was actually just searching for this same thing on Google. I recently started a new project that LiveView would have been great for, but the fact that I need a native iOS/Android app caused me to go with Socket.IO instead for the backend. It seems likely to me that there is a way to use Phoenix channels with web, iOS, and Android.. but there isn't a lot of good information on doing it that I've been able to find. Edit: I realize you could just use regular web sockets with Phoenix to do what Socket.IO does. But my confusion comes from actually getting it all to play nice with a LiveView front end, as well as a native app front end.
- klohto 5y agoOut of my head (just amateur in Phoenix right now) you could just leverage the API endpoints in Phoenix and implement the iOS and Android frontend with them. The Views are decoupled. So you can have the business logic, as you would normally do, inside Phoenix, then the API on top of this logic, and then you could either implement the whole LiveView workflow on top of the API or just directly on top of the business logic (if you’re feeling kinky but it invalidates the architecture Phoenix sets up for you). The Getting Started guide on Phoenix has a lot of useful material even for your use case. I might be missing something crucial though :)
- chrismccord 5y agoPhoenix channels is similar to socket.io, except we multiplex the channels with their own events, vs socket io that creates a single bidirectional "channel" with events. So you can think of channels as namespaced socket.io, with the server side allowing isolated and concurrent message handlers to live. The channel docs give a solid overview of the server side, and we have a listing of third-party channels clients for most platforms here: https://hexdocs.pm/phoenix/1.6.0-rc.1/channels.html#client-libraries https://hexdocs.pm/phoenix/1.6.0-rc.1/channels.html#client-l...
- hervature 5y agoHey Chris, excellent work. Very excited about 1.6 and LiveView. If you update your Programming Phoenix, I would certainly pay again.
- nightpool 5y agoI've tried to get into Phoenix a few different times, but I've always been stymied by the unfamiliarity of Elixir's syntax, especially codebases that made heavy use of composition and guard clauses, meaning that the business logic was scattered across a half-dozen different files which had to be read in sequence to understand a single web request. This was a big let-down from the (to my mind) very straight-forward nature of MVC code and project structure that Rails pioneered. Do you have any tips for structuring Phoenix projects or approaching these kinds of codebases?
- sodapopcan 5y agoI'm not sure I follow. Phoenix is also MVC and its request model is far simpler than Rails'. In Rails we have controllers, we have callbacks (or "filters" as they are called now), and we have "middleware". That's three concepts right there! In Phoenix, we have a connection struct that flows through a pipeline of "plugs". Plugs are just functions that transform said connection. Each part of the request pipeline is implemented as a plug. You can create your own plugs and "plug" them in where you see fit. Read more here: https://hexdocs.pm/phoenix/plug.html https://hexdocs.pm/phoenix/plug.html Of course, LiveView isn't MVC in the classic sense, but it still uses plugs. Its goal is to simplify the SPA which I'd say it does a particular good job of. [Edited to fix part of a sentence I deleted by accident]
- joelbluminator 5y agoI want to try Phoenix but one of my app's classes is called Butt (it's an app about the human body), what will happen when I need to use plugs? Will it become ButtPlug? I can't have that on my app.
- erinan 5y agoThis has most likely to do with the codebase itself rather than with Elixir or Phoenix in your case. And having to go through a few files to understand how a request is handled is not out of the ordinary in an app, especially if it's grown over the years?
- davidw 5y agoBusiness-wise, what do you think the sweet spots are for LiveView, Phoenix and Elixir right now? I love the BEAM ecosystem (I've been using it since 2004, on and off), but for a lot of places, Rails is still a great place to start. What kinds of applications have you seen where all the BEAM features just make Phoenix et al not just a little snappier, but a clear winner?
- innocentoldguy 5y agoThe sweet spots for me are: 1. It is much easier to trace things through the entire Phoenix stack than it is in Rails. It is also much easier to add things to the Phoenix stack using plugs. 2. Elixir is concurrent, whereas Ruby is not, so when performing long-running processes, you can just do them in Elixir/Phoenix without having to rely on workarounds like Sidekiq, Resque, RabbitMQ, etc. 3. Writing multi-threaded applications is much easier in Elixir than many (if not all) OO languages. 4. Pattern-matching for variables and functions, and binary pattern-matching for parsing text. 5. Mix. 6. BEAM, OTP, and supervision trees.
- davidw 5y agoLooking more at things like #2. Sidekiq isn't terrible though, and if you get big enough, you're going to want some more management than just spawning a BEAM process to do something. What have people settled on for that with Elixir/Erlang?
- hanrelan 5y agoYou could use something like oban: https://github.com/sorentwo/oban https://github.com/sorentwo/oban
- tptacek 5y agoSidekiq is great, but it is a thing you have to think about (in particular, how you're shuttling state from workers to a place where front-end can see it). The big win with Phoenix as I understand is not having to think about it at all: it has a natural expression in the language and the platform, and that expression is performant.
- scraplab 5y agoHi Chris - this is superb, really pleased to see LiveView getting so much attention, and thanks for all your hard work. Can you talk a little about the current story with deployments and managing state across/during those? Obviously Erlang/OTP supports hot upgrades, but those are hard to design correctly and not supported by container/VM environments like Heroku and (I presume?) Fly.io.
- modal-soul 5y agoIf LiveView is backed by PubSub, then I think you can offload persistence to Redis.
- ramchip 5y agoLiveView in its standard configuration does not use Redis, it uses built-in Erlang distribution. But you can use Redis if you want to or if direct connections between nodes aren't possible.
- ramchip 5y agoYou can store state client-side. Say you have a view to edit users, with a modal dialog. A typical LiveView app will change the URL when you open the modal, so it's like /users?action=edit&user=bob. When a server goes down the client reconnects, and the LV receives the URL params in its handle_param callback, so it can recover the earlier state. Forms recover automatically in a similar way. With this and a DB to store permanent data, an LV app can be deployed just like any other standard container app without user impact.
- chrismccord 5y agoHot upgrades are a powerful and essential feature – when you have hard requirements for it. As you said, hot upgrades aren't simple and introduce a lot of work to get right. I like to tell folks, imagine you are building a pusher.com competitor, so your customers are paying for you to host active connections for their end-users. In this scenario, bouncing hundreds of thousands of connections for a cold deploy is a terrible offering because your clients are paying you or that reliable wire to their user's browser. Hot upgrades makes total sense here. Equally, if you're building a game server in Elixir, you likely don't want to teardown and rebuild your world state and bounce connected players. So you opt-in to this complexity when you have a clear requirement for it. They other key point in this, is in either hot upgrade or cold deploy cases, you still have to design your stateful system to recover from complete restart. Servers catch on fire and things go bad sometimes, so the cold deploy approach of rebuilding the state on restart is not only completely viable by itself, but you're doing it anyway even with hot upgrades. Hope that helps!
- whitepoplar 5y agoIf one wanted to learn LiveView today, what's the best resource to learn? Also, will there be improvements to the LiveView latency story (if it's even possible) when providing a service to a global audience? Thanks for all your work!
- mrkurt 5y agoNon technical Fly.io founder here: LiveView and Elixir work very well distributed all over the world. Here's an example app I fumbled my way through to show it in action: https://liveview-counter.fly.dev/ https://liveview-counter.fly.dev/
- tptacek 5y ago"Non-technical Fly.io founder", who do you think you're kidding? You have more commits than me in the last week.
- whitepoplar 5y agoHaven't played around with Fly yet, but it seems amazingly well-suited to LiveView apps and y'all seem like great people in general. Is there a Fly solution for if someone needed a big swinging...database? I guess one fear is getting locked into Fly + LiveView given latency concerns with alternative hosting providers, but outgrowing Fly's database offerings.
- mrkurt 5y agoOur Postgres is pretty great up to about 500GB. We'll be pushing that higher over the next year, but we have several customers using Crunchy Data (https://www.crunchydata.com/products/crunchy-bridge/ https://www.crunchydata.com/products/crunchy-bridge/) in conjunction with their Fly.io apps. We intentionally give you super user access to your DBs so it's easy to migrate or spin up your own replicas. Our bet is that _most_ people won't outgrow our Postgres but having an escape hatch is still very comforting. We previously worked on Compose.com. We, at least, understand how to manage huge databases when the time comes.
- staticelf 5y agoAre you guys looking into the Web Transport protocol for the future? Right now you have to tunnel the websocket connections over http2 and it will probably be the same for http3 afaik. I know there is this work in progress (https://w3c.github.io/webtransport/ https://w3c.github.io/webtransport/) and websockets are probably fine for a long time but sooner or later (unless there is an update to websockets) it will probably be faster to just do normal http requests and listen on server sent events. What are your thoughts for Liveview for the future? Will it forever stay on websockets or would you be open to change the underlying technology if / when new stuff becomes available?
- chrismccord 5y agoPhoenix Channels (which LiveView is built on) is transport agnostic, so as soon as we can open a pipe from the browser's JS environment, and listen on the server, we could have a `Phoenix.Transports.WebTransport`. All the existing user-land code and LV apis remain unchanged :)
- staticelf 5y agoThat is something I suspected. When I first saw your talk about LiveView on youtube my mind was completely blown away. It is such an awesome technology.
- jarpineh 5y agoHi. I got a couple of things: I seem to remember in the original announcement presentation there was a demo of SVG being updated inside a page 60 times per second. All from server. Did this actually become feasible? I’m thinking graphs and maps with live data. I might not need as smooth animation there. Though that could make for nice dashboards. Other bit that interests me is web apps for long running tasks. What’s the story in Phoenix and Elixir land for handling external shell processes from web requests? I’m trying to do lightweight job control without investing into separate systems for processing pipelines, CI/CD and the like. Thank you for Live View. It continues to be an inspiration even though I haven’t yet had a chance to dive into server side of it.
- chrismccord 5y agoThe 60fps rainbow works as a fun stress test demo, but really you should not be pushing events down the wire every 16ms to animate something on the client :) That said, you are right that SVG charts/maps are a surprisingly fantastic fit for LiveView. You could actually render a fully interactive and dynamically updating chart by only sending SVGs – and it will probably send less data than hydrating the same client-side chart with JSON! Check out the Context Chart lib for some examples. They have some links running LiveView examples if you scroll down: https://contex-charts.org https://contex-charts.org > What’s the story in Phoenix and Elixir land for handling external shell processes from web requests Great story here thru erlang ports. I'm a big fan of the Porcelain library which wraps ports with some nice features on top: https://github.com/alco/porcelain https://github.com/alco/porcelain
- jarpineh 5y agoHey, thanks a lot. These are great tips. Context Charts look really good and lightweight to run. Porcelain seems verty promising. Guess I’ll start with one of the tutorials elsewhere in the thread. Good info here all around. Much appreciated.
- sgrytoyr 5y agoAlmost every time I see a discussion about LiveView there’s someone complaining about the issue of latency/lag, and how it makes LiveView unsuitable for real-world applications. From what I understand, the issue is that every event that happens on the client (say, a click) has to make a roundtrip to the server before the UI can be updated. If latency is high, this can make for a poor user experience, the argument goes. As the creator of LiveView, what’s your take on this? Is it a real and difficult-to-solve issue, or do people just not see "the LiveView way" of solving it? I think LiveView looks amazing, but this possible issue (in addition to chronic lack of time) has made me a little unsure of whether it’s ready to use for a real project. Thanks for creating Phoenix, btw!
- ignoramous 5y agoNot OP, but: > If latency is high, this can make for a poor user experience, the argument goes. Deploy auto-scaling servers closer to your users: Use fly.io (or any other competent edge platform, really).
- akoutmos 5y agoFor a lot of the LiveView applications that I write (which is actually quite a few these days), I will usually lean on something like AlpineJS for frontend specific interactions, and my LiveView state is for things that require backend state. For example, if I have a flag to show/hide a modal to confirm a resource delete, the show/hide flag would live in AlpineJS, while the resource I was deleting would live in the state of my LiveView. This way, there are no round trips to the server over websocket to toggle the modal. Hopefully that example makes sense :).
- yewenjie 5y agoHi, really excited about the new release - Heex and Esbuild support is fantastic. Do you think it is possible for newcomers to pick up Phoenix and at the same time learn how frameworks work? For example, FastAPI [0] is a widely extensive Python framework yet its documentation essentially is just a long tutorial which explains basic web-development concepts while teaching its core. OTOH, almost all Phoenix learning material I have come across so far are targeted to experienced devs (especially Rails). I really love that Phoenix is opinionated but I feel like there should be some ways to learn about the rationale behind those choices, without having 10 years of development intuition. [0] https://fastapi.tiangolo.com/ https://fastapi.tiangolo.com/
- PKop 5y agoTake a look at these courses on Elixir/OTP[0] and Phoenix LiveView[1] from Pragmatic Studio. Both of them together I felt gave a well paced overview of elixir servers, and Phoenix framework from a good starting point even for beginners as you seem to be looking for. There's a combo price deal if you by both courses. [0] https://pragmaticstudio.com/courses/elixir https://pragmaticstudio.com/courses/elixir [1] https://pragmaticstudio.com/courses/phoenix-liveview https://pragmaticstudio.com/courses/phoenix-liveview
- neillyons 5y agoThis article really helped me. It basically builds Phoenix from the ground up. Starting with "hello world" in the terminal. http://www.petecorey.com/blog/2019/05/20/minimum-viable-phoenix/ http://www.petecorey.com/blog/2019/05/20/minimum-viable-phoe...
- chrismccord 5y agoIt's absolutely possible, but you are right our docs and guides are more tailored to folks already familiar with web development. I would love to see more Elixir and Phoenix content for someone who has never written a program before. I do think we'll start seeing more of these kinds of efforts, but it's the nature of the age of the ecosystem and adoption cycle that content is initially tailored to more advanced users.
- jherdman 5y agoHi Chris. We've been using LiveView to build a new app at Precision Nutrition and are largely quite happy with it so far. One concern we keep coming back to is that of the need for constant connectivity in order for the app to work. I'll throw up the disclaimer here that I've not spike on how to handle network disconnects. That said, we've had a few of our internal users lose their connection to the web socket, and the app just beach balls. You can't do anything. Another example we keep coming back to is a user going onto a subway. How do you envision spotty connections being handled long term?
- mrkurt 5y agoI've been experimenting with some progressive enhancement style HTML. You can build forms that post the "normal" way, then get the full liveview experience when the socket is mounted. If an app can be reduced to just CRUD, I think it works very well.
- chrismccord 5y agoLiveView will automatically recover the connection, but you are correct it requires a connection to allow interactivity, but this isn't different from being unable to post a tweet while driving under the subway. The interesting thing about the subway usecase is even google docs last I checked will go into read-only mode when the connection is lost, so I don't consider this scenario particular different than the status quo. LiveView adds a `phx-disconnected` class, which is what I assumed you mean by beachball, and interactions are paused while the user awaits the UI to tell them they are good. This is all driven by your CSS and you can also hook into the connection life-cycle with a few lines of JS, so the app should be telling the user "Reconnecting..." vs it appearing broken, so this is really up to your UX folks. By default new phx apps make use of the topbar library so any page loading event or dropped connection will show the loading bar/spinner up top. As far as spotty connections go, when I try simulating 30% packet loss, my LiveView WebSocket connections have no perceptible degradation, so it's hard to say where the cut off is. You can also fall back to long-polling which may benefit very edge users, but I would only do so if absolutely necessary. Having said all that, one thing we are upfront about in general is LiveView is obviously not a good fit applications that require offline support :)
- losvedir 5y ago1. LiveView looks incredible! But Phoenix is also great at standard JSON APIs. How do you think about the decision between using LiveView vs a SPA with a Phoenix API backend? I'm not too sure about the limits or future vision of LiveView. Do you think there's a place for SPAs, or is the goal for LiveView to be able to replace them in almost all use cases? 2. What's your dev environment like? VSCode? What extensions, etc? 3. Excited to see you at fly.io! I think I saw a tweet about them wanting to make deploying Livebooks (built on LiveView) easy. Any news on that front?
- chrismccord 5y ago1. Thanks! You are right Phoenix also great for APIs, and this story is pretty much baked as far as Phoenix specific features go. There's absolutely a place for SPAs, and the JavaScript ecosystem has number of great options. Anything requiring offline support is obviously out for LiveView, as well as highly complex UIs, tho that is pretty vague. For example, I wouldn't build Google Docs or Google Maps with LiveView, but as we've seen with Livebook, you can do a shocking amount of complex things with a LiveView application and a few escape hatches to JS. We're still finding out where the bounds are. Our goal isn't to replace SPAs, but I do think we'll obviate them for a large class of applications. 2. VSCode with VIM keybindings. I bounce from vim/emacs/vscode (all w/ vim emulation), but vscode has stuck pretty well for the last couple years. Much to my chagrin, it's faster than terminal emacs. 3. No news quite yet, but we're working on it. Stay tuned!
- 1_player 5y agoPhoenix 1.6 has been in alpha/release candidate for a few weeks now. Just curious, what issues are blocking the stable release of 1.6.0? I've checked GitHub but I haven't found any major outstanding bugs waiting to be ironed out.
- chrismccord 5y agoNo blockers. We're simply giving folks time to try things out and report issues. No show stoppers at the moment so I imagine final release won't be far off!
- ignoramous 5y agoHi Chris, A someone who's familiar with Kotlin, I can see how Erlang's processes and mailboxes would work. The question I have is, you mention Phoenix maxed out available FDs but RoR would have struggled. I didn't quite get what those fundamental differences are that prevent RoR/Ruby from scaling-up io-bound workloads as effortlessly as Elixir/Erlang, given you point out that sync.rb was built upon a similarly capable event-io lib. Also, if I may, what do you make of your former employers 37 Signal's turbo (hotwire) with RoR? Does the vision you have for Phoenix with LiveView match what you see them doing with hotwire? How do the solutions compare if you have had a chance to take a look? Thanks.
- strzibny 5y agoI am not Chris, but maybe I can answer the Hotwire and LiveView difference. Hotwire is building stuff from regular HTTP requests (ala AJAX) and uses WebSockets only for Turbo Streams. LiveView is all on WebSockets. You can think of Hotwire as being stateless and stateful when required. LiveView is stateful. Hotwire exchanges HTML snippets at various length whereas LiveView tries to do a very minimal diff for an update. WebSockets would be faster for your regular updates, but you need to keep a connection open. In other stacks this might not be ideal, but it's what Beam is made for.
- turtlebits 5y agoJust getting started into Liveview, what confuses me is the proper way to integrate javascript. The JavaScript interoperability documentation page isn't really helpful. A simple case for me is using hotkeys to submit a form. Couldn't figure out a way to trigger a phx-submit from a onkeydown handler.
- jakeva 5y agoI might try setting a mounted hook on the element with something like this.el.addEventListener('onkeydown', function (event) { this.el.dispatchEvent(new Event('change', { 'bubbles': true })) }, true);
- chrismccord 5y agoIf you think the docs can be improved, please let us know. You can also find us on elixir-slack or elixirforum.com to ask for help. This should get you started: //<input type="text" name="body" phx-hook="SubmitOnEnter"/> let Hooks = {} Hooks.SubmitOnEnter = { mounted(){ this.el.addEventListener("keydown", e => { if(e.key === "Enter"){ this.el.form.dispatchEvent(new Event("submit", {bubbles: true})) } }) } } ... let liveSocket = new LiveSocket("/live", Socket, {hooks: Hooks, ...})
- skybrian 5y agoI'm wondering how this framework handles user feedback for network errors and delays? It seems like your changes aren't really committed until they hit the database, but there are a lot of intermediate states.
- chrismccord 5y agoWe have optimistic UI features where we'll apply a css class to the interacted element, lock that DOM container for inbound updates, and only remove the class when that specific interaction is acknowledged by the server. We can also swap text in a similar fashion. The DockYard blog I linked up thread covers these things in detail.
- Omnipresent 5y agoWhat resources would you recommend for someone new to Phoenix, LiveView, Elixir to get started on this stack?
- mrkurt 5y agoThis is a pretty good liveview tutorial: https://github.com/dwyl/phoenix-liveview-counter-tutorial https://github.com/dwyl/phoenix-liveview-counter-tutorial We also have a hiring project that's designed to ease people in to Phoenix + LiveView. We extracted this from a real app and tried to make it as simple as possible to work on: https://github.com/fly-hiring/phoenix-full-stack-work-sample https://github.com/fly-hiring/phoenix-full-stack-work-sample
- iudqnolq 5y agoWhat sort of experience level are you hiring for? I've been teaching myself elixir and liveview over the past year for my first job (building dashboards for a non-technical nonprofit) and I've been hoping to transition to working somewhere technical but I have no idea how to do it. Thanks!
- anonymousDan 5y agoHow do you handle issues of consistency once you need to scale your app server across multiple nodes? Under the assumption that in the past much of this would be handled in the database, are there any guidelines regarding what state to maintain in the app server in order to avoid any issues? Or is this just a non-problem?
- bugmen0t 5y agoHEEx looks awesome. How does compilation work? Does it properly & contextually encode/escape to avoid XSS? I'd love to learn more about the inner workings.
- rishav_sharan 5y agoOne question here; is there anything special about Elixir/Beam which makes Liveview on Phoenix a great fit? Or can LiveViews be done on more performant languages like Go, Rust etc? I am just surprised why we don't see more LiveView implementations in other languages?
- Traubenfuchs 5y ago> I am just surprised why we don't see more X implementations in other languages? X probably doesn't have the mainstream appeal some people think it should have.
- neillyons 5y agoLaravel has LiveWire https://laravel-livewire.com https://laravel-livewire.com which works in a similar way.
- chrismccord 5y agoThere has been a large number of LiveView-like solutions pop up that are inspired by what we're doing. I tried to outline what makes Elixir uniquely suited to handle this kind of thing in the post, but I'll try to distill it here: 1. The concurrency and distribution model. Processes (light weight green threads) and extremely cheap, isolated, and concurrent. Process can message each other, and messaging is location transparent. So you can send a message to another process on another Elixir server using the exact same primitives as sending a message to a process on the local server. This allows for all kinds of things that are hard or not reasonably possible in other platforms: - Start a process on a node in us-east1, and message it from Tokyo. This is simply built-in. - Run a primary DB in us-east1, and RPC from your Tokyo instances to perform writes. The RPC mechanism is again built in. You have code running on another node, and you simply run your code over there and get the result. There's no marshaling of data structures, deploying message queues, protocol buffers, etc - Using Phoenix Pubsub, broadcast a message from anywhere in the cluster, `PubSub.broadcat(:my_pub, {:new_msg, "hi!})` and it will arrive to all instances who are subscribed, anywhere This kind of stuff can be made to work well in Go and Rust, but you need to bring in libraries and do more work. They are absolutely great at "network programs", but lacking the distribution primitives means libraries and solutions are usually more bespoke vs Elixir where everyone in the community simply uses what is provided out of the box. So there is no interplay of ops or dependencies to try to reconcile. 2. Processes support stateful applications. Most of the LiveView-like solutions still go over stateless HTTP because websockets and cheap concurrency aren't as viable. This drastically limits what you can do efficiency wise. For example, our diffing engine requires state to live on the server so we know what changed. If you simulate LiveView over HTTP by sending all the state from the client for every interaction, you are sending way more data, doing all the HTTP authentication, fetching the world, then sending the entire template back. 3. Process are preemptively scheduled and load-balanced on IO and CPU. This allows your LiveViews to perform blocking CPU bound work and the scheduler will make sure every other user gets their fair time share. In other languages like Node where you rely on evented IO, any CPU bound work blocks the entire program. 4. Processes are isolated. On the evented IO example, imagine your websocket handler in Node.js has an uncaught exception caused by a single user interaction. It brings down the connections for all connected users. In Elixir, all processes are isolated, garbage collected in isolation, so you aren't jumping thru hoops to handle these kinds of degradation modes. Hope that helps!
- slydo 5y agoHi Chris, two questions about phoenix and liveview. I would like the web app to have good offline support and use localstorage for backing when the connection goes down (re-upload when connection is back up). It it in anyway feasible to add some middleware to the client connection handling of liveview so that it still plays well with it's features? I've read that it is possible to drop in some bits of JS here and there into the liveview powered page. Is it also possible to do it the other way around and go to drop in liveview "components" into an existing SPA? Throwing away my existing SPA code is quite a loss, but the liveview appeal is certainly there for other parts of the website. Thanks for the great work on phoenix, it looks quite attractive.