DEV Community

Discussion on: Welcome to Fiber — an Express.js styled web framework written in Go with ️

Collapse
 
davidmz profile image
Давид Мзареулян • Edited

Why do we need prefork in Go? Isn't regular gorutines enough?

Collapse
 
kataras profile image
Info Comment hidden by post author - thread only visible in this permalink
Gerasimos (Makis) Maropoulos • Edited

In short, prefork is done through Unix' SO_REUSEADDR and it does not work on Windows hosts. You can implement preforking on any web framework, including the standard net/http. A good library (that iris uses too) is tcplisten by @valyala the creator of fasthttp and a good friend. Example code:

 listenerCfg := tcplisten.Config{
    ReusePort:   true,
    DeferAccept: true,
    FastOpen:    true,
}



for i:=0;i<runtime.NumCPU();i++ {

    /* 1. inline servers, share the same binary.
    ln, err := listenerCfg.NewListener("tcp4", ":8080")
    if err != nil {
       panic(err)
    }
    go http.Serve(ln, yourMux_Router)
    */

    /*2. Start the same binary with an argument of `--prefork`
         or anything that will mark the server as a fork. 

        https://github.com/gofiber/fiber/blob/master/application.go#L46
        https://github.com/gofiber/fiber/blob/master/application.go#L378
        and finally:
        https://github.com/gofiber/fiber/blob/master/application.go#L469
    */


}

http.ListenAndServe(":8080", yourMux_Router) // blocks. 

Also, see the discussion at the fasthttp repository itself:

I noticed that you recently removed the prefork method from your TechEmpower
benchmark code. Do you no longer believe the prefork method to offer better performance? by @manthedan at github.com/valyala/fasthttp/issues...

Collapse
 
fenny profile image
Fenny

Preforking is making use of multiple socket listeners on OS level. We explained preforking with images in our docs fiber.wiki/application#prefork

Collapse
 
davidmz profile image
Давид Мзареулян

Does prefork mean that workers are executed in different processes (not goroutines) and cannot communicate or share memory with each other?

Thread Thread
 
fenny profile image
Fenny • Edited

This is correct, preforking is for specific use cases. If you work with an external database it should be no problem, because you can pool connections. You can see a good result here: techempower.com/benchmarks/#sectio...

Some comments have been hidden by the post's author - find out more