ardanlabs / service

Starter-kit for writing services in Go using Kubernetes.
https://www.ardanlabs.com
Apache License 2.0
3.4k stars 612 forks source link

error when run multiple instances #381

Closed himynamej closed 3 weeks ago

himynamej commented 3 weeks ago

in user cash business/domain/userbus/stores/usercache/usercache.go when we run multiple instances with k8s It can lead to errors when we run update or delete in one instance and cache it. another instance is not informed of this change and can Give us wrong information. for example we create user in one instance and update it in another instance when we want to get QueryByID each instances have there own version of it. // Create inserts a new user into the database. func (s *Store) Create(ctx context.Context, usr userbus.User) error { if err := s.storer.Create(ctx, usr); err != nil { return err }

s.writeCache(usr)

return nil

}

// Update replaces a user document in the database. func (s *Store) Update(ctx context.Context, usr userbus.User) error { if err := s.storer.Update(ctx, usr); err != nil { return err }

s.writeCache(usr)

return nil

} // QueryByID gets the specified user from the database. func (s *Store) QueryByID(ctx context.Context, userID uuid.UUID) (userbus.User, error) { cachedUsr, ok := s.readCache(userID.String()) if ok { return cachedUsr, nil }

usr, err := s.storer.QueryByID(ctx, userID)
if err != nil {
    return userbus.User{}, err
}

s.writeCache(usr)

return usr, nil

}

ardan-bkennedy commented 3 weeks ago

That cache was for an example. I wouldn't use it. I would find a caching package that is more robust. Plus you need the ability to remove items from the cache over time.

In a multi-instance the cache is local and could be dirty. In this situation this is where redis or badger comes in.