Why is this simple go sqlite statement sometimes taking 5 seconds?

145 Views Asked by At

This is a small chat app. Here is the function:

var msgsStatement *sql.Stmt
func handleMessages() {
    for {
        msg := <-broadcast
        log.Println(msg)
        start := time.Now().UnixNano()
        msgsStatement.Exec(&msg.Username, &msg.Message, &msg.Timestamp)
        end := time.Now().UnixNano()
        log.Println("Data write takes ", end-start, " nanoseconds.")
        for client := range clients {
            err := client.WriteJSON(msg)
            if err != nil {
                log.Printf("error: %v", err)
                client.Close()
                delete(clients, client)
            }
        }
    }
}

This might give a console output something like this:

2020/04/21 19:06:56 {1587467216 user1 1}
2020/04/21 19:06:56 Data write takes  6982800  nanoseconds.
2020/04/21 19:07:24 {1587467244 user2 ff}
2020/04/21 19:07:30 Data write takes  5037668900  nanoseconds.

As you can see the first time it takes 6 milliseconds but the second time it takes 5 seconds which is weird for such a small data write. When this happens is seemingly random.

I am using go-sqlite3 db. The db is very small right now, the messages table has around 50 rows. There are no indexes. These are the columns in the db:

msgsStatement, _ = database.Prepare("CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, username TEXT, message TEXT, timestamp INTEGER)")

Full code: https://github.com/mismaah-abdulla/Chatapp-Backend/blob/d70123cb73bfae5c01a3e7605ec254561ce1a749/src/main.go

0

There are 0 best solutions below