1

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

mismaah
  • 344
  • 5
  • 21
  • Hi, can you detail it more? like: how many rows are there in db, your db version, what row no for user1 and user2 when it happens, what are your db indexes, what is the primary key. Because problem like this usually happens under specific condition. – Nikko Khresna Apr 21 '20 at 19:46
  • @NikkoKhresna More details added. – mismaah Apr 21 '20 at 23:16

0 Answers0